search for in the  
<StringsObjects>
Last updated: Thu, 19 May 2005

Arrays

An array in PHP is actually an ordered map. A map is a type that maps values to keys. This type is optimized in several ways, so you can use it as a real array, or a list (vector), hashtable (which is an implementation of a map), dictionary, collection, stack, queue and probably more. Because you can have another PHP array as a value, you can also quite easily simulate trees.

Explanation of those data structures is beyond the scope of this manual, but you'll find at least one example for each of them. For more information we refer you to external literature about this broad topic.

Syntax

Specifying with array()

An array can be created by the array() language-construct. It takes a certain number of comma-separated key => value pairs.

array( [key =>] value
     , ...
     )
// key may be an integer or string
// value may be any value

<?php
$arr
= array("foo" => "bar", 12 => true);

echo
$arr["foo"]; // bar
echo $arr[12];    // 1
?>

A key may be either an integer or a string. If a key is the standard representation of an integer, it will be interpreted as such (i.e. "8" will be interpreted as 8, while "08" will be interpreted as "08"). Floats in key are truncated to integer. There are no different indexed and associative array types in PHP; there is only one array type, which can both contain integer and string indices.

A value can be of any PHP type.

<?php
$arr
= array("somearray" => array(6 => 5, 13 => 9, "a" => 42));

echo
$arr["somearray"][6];    // 5
echo $arr["somearray"][13];  // 9
echo $arr["somearray"]["a"];  // 42
?>

If you do not specify a key for a given value, then the maximum of the integer indices is taken, and the new key will be that maximum value + 1. If you specify a key that already has a value assigned to it, that value will be overwritten.

<?php
// This array is the same as ...
array(5 => 43, 32, 56, "b" => 12);

// ...this array
array(5 => 43, 6 => 32, 7 => 56, "b" => 12);
?>

Warning

As of PHP 4.3.0, the index generation behaviour described above has changed. Now, if you append to an array in which the current maximum key is negative, then the next key created will be zero (0). Before, the new index would have been set to the largest existing key + 1, the same as positive indices are.

Using TRUE as a key will evaluate to integer 1 as key. Using FALSE as a key will evaluate to integer 0 as key. Using NULL as a key will evaluate to the empty string. Using the empty string as key will create (or overwrite) a key with the empty string and its value; it is not the same as using empty brackets.

You cannot use arrays or objects as keys. Doing so will result in a warning: Illegal offset type.

Creating/modifying with square-bracket syntax

You can also modify an existing array by explicitly setting values in it.

This is done by assigning values to the array while specifying the key in brackets. You can also omit the key, add an empty pair of brackets ("[]") to the variable name in that case.
$arr[key] = value;
$arr[] = value;
// key may be an integer or string
// value may be any value
If $arr doesn't exist yet, it will be created. So this is also an alternative way to specify an array. To change a certain value, just assign a new value to an element specified with its key. If you want to remove a key/value pair, you need to unset() it.

<?php
$arr
= array(5 => 1, 12 => 2);

$arr[] = 56;    // This is the same as $arr[13] = 56;
               // at this point of the script

$arr["x"] = 42; // This adds a new element to
               // the array with key "x"
              
unset($arr[5]); // This removes the element from the array

unset($arr);    // This deletes the whole array
?>

Note: As mentioned above, if you provide the brackets with no key specified, then the maximum of the existing integer indices is taken, and the new key will be that maximum value + 1 . If no integer indices exist yet, the key will be 0 (zero). If you specify a key that already has a value assigned to it, that value will be overwritten.

Warning

As of PHP 4.3.0, the index generation behaviour described above has changed. Now, if you append to an array in which the current maximum key is negative, then the next key created will be zero (0). Before, the new index would have been set to the largest existing key + 1, the same as positive indices are.

Note that the maximum integer key used for this need not currently exist in the array. It simply must have existed in the array at some time since the last time the array was re-indexed. The following example illustrates:

<?php
// Create a simple array.
$array = array(1, 2, 3, 4, 5);
print_r($array);

// Now delete every item, but leave the array itself intact:
foreach ($array as $i => $value) {
   unset(
$array[$i]);
}
print_r($array);

// Append an item (note that the new key is 5, instead of 0 as you
// might expect).
$array[] = 6;
print_r($array);

// Re-index:
$array = array_values($array);
$array[] = 7;
print_r($array);
?>

The above example will output:

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
)
Array
(
)
Array
(
    [5] => 6
)
Array
(
    [0] => 6
    [1] => 7
)

Useful functions

There are quite a few useful functions for working with arrays. See the array functions section.

Note: The unset() function allows unsetting keys of an array. Be aware that the array will NOT be reindexed. If you only use "usual integer indices" (starting from zero, increasing by one), you can achieve the reindex effect by using array_values().

<?php
$a
= array(1 => 'one', 2 => 'two', 3 => 'three');
unset(
$a[2]);
/* will produce an array that would have been defined as
   $a = array(1 => 'one', 3 => 'three');
   and NOT
   $a = array(1 => 'one', 2 =>'three');
*/

$b = array_values($a);
// Now $b is array(0 => 'one', 1 =>'three')
?>

The foreach control structure exists specifically for arrays. It provides an easy way to traverse an array.

Array do's and don'ts

Why is $foo[bar] wrong?

You should always use quotes around a string literal array index. For example, use $foo['bar'] and not $foo[bar]. But why is $foo[bar] wrong? You might have seen the following syntax in old scripts:

<?php
$foo
[bar] = 'enemy';
echo
$foo[bar];
// etc
?>

This is wrong, but it works. Then, why is it wrong? The reason is that this code has an undefined constant (bar) rather than a string ('bar' - notice the quotes), and PHP may in future define constants which, unfortunately for your code, have the same name. It works because PHP automatically converts a bare string (an unquoted string which does not correspond to any known symbol) into a string which contains the bare string. For instance, if there is no defined constant named bar, then PHP will substitute in the string 'bar' and use that.

Note: This does not mean to always quote the key. You do not want to quote keys which are constants or variables, as this will prevent PHP from interpreting them.

<?php
error_reporting
(E_ALL);
ini_set('display_errors', true);
ini_set('html_errors', false);
// Simple array:
$array = array(1, 2);
$count = count($array);
for (
$i = 0; $i < $count; $i++) {
   echo
"\nChecking $i: \n";
   echo
"Bad: " . $array['$i'] . "\n";
   echo
"Good: " . $array[$i] . "\n";
   echo
"Bad: {$array['$i']}\n";
   echo
"Good: {$array[$i]}\n";
}
?>

Note: The above example will output:

Checking 0: 
Notice: Undefined index:  $i in /path/to/script.html on line 9
Bad: 
Good: 1
Notice: Undefined index:  $i in /path/to/script.html on line 11
Bad: 
Good: 1

Checking 1: 
Notice: Undefined index:  $i in /path/to/script.html on line 9
Bad: 
Good: 2
Notice: Undefined index:  $i in /path/to/script.html on line 11
Bad: 
Good: 2

More examples to demonstrate this fact:

<?php
// Let's show all errors
error_reporting(E_ALL);

$arr = array('fruit' => 'apple', 'veggie' => 'carrot');

// Correct
print $arr['fruit'];  // apple
print $arr['veggie']; // carrot

// Incorrect.  This works but also throws a PHP error of
// level E_NOTICE because of an undefined constant named fruit
//
// Notice: Use of undefined constant fruit - assumed 'fruit' in...
print $arr[fruit];    // apple

// Let's define a constant to demonstrate what's going on.  We
// will assign value 'veggie' to a constant named fruit.
define('fruit', 'veggie');

// Notice the difference now
print $arr['fruit'];  // apple
print $arr[fruit];    // carrot

// The following is okay as it's inside a string.  Constants are not
// looked for within strings so no E_NOTICE error here
print "Hello $arr[fruit]";      // Hello apple

// With one exception, braces surrounding arrays within strings
// allows constants to be looked for
print "Hello {$arr[fruit]}";    // Hello carrot
print "Hello {$arr['fruit']}"// Hello apple

// This will not work, results in a parse error such as:
// Parse error: parse error, expecting T_STRING' or T_VARIABLE' or T_NUM_STRING'
// This of course applies to using autoglobals in strings as well
print "Hello $arr['fruit']";
print
"Hello $_GET['foo']";

// Concatenation is another option
print "Hello " . $arr['fruit']; // Hello apple
?>

When you turn error_reporting() up to show E_NOTICE level errors (such as setting it to E_ALL) then you will see these errors. By default, error_reporting is turned down to not show them.

As stated in the syntax section, there must be an expression between the square brackets ('[' and ']'). That means that you can write things like this:

<?php
echo $arr[somefunc($bar)];
?>

This is an example of using a function return value as the array index. PHP also knows about constants, as you may have seen the E_* ones before.

<?php
$error_descriptions
[E_ERROR]  = "A fatal error has occured";
$error_descriptions[E_WARNING] = "PHP issued a warning";
$error_descriptions[E_NOTICE]  = "This is just an informal notice";
?>

Note that E_ERROR is also a valid identifier, just like bar in the first example. But the last example is in fact the same as writing:

<?php
$error_descriptions
[1] = "A fatal error has occured";
$error_descriptions[2] = "PHP issued a warning";
$error_descriptions[8] = "This is just an informal notice";
?>

because E_ERROR equals 1, etc.

As we already explained in the above examples, $foo[bar] still works but is wrong. It works, because bar is due to its syntax expected to be a constant expression. However, in this case no constant with the name bar exists. PHP now assumes that you meant bar literally, as the string "bar", but that you forgot to write the quotes.

So why is it bad then?

At some point in the future, the PHP team might want to add another constant or keyword, or you may introduce another constant into your application, and then you get in trouble. For example, you already cannot use the words empty and default this way, since they are special reserved keywords.

Note: To reiterate, inside a double-quoted string, it's valid to not surround array indexes with quotes so "$foo[bar]" is valid. See the above examples for details on why as well as the section on variable parsing in strings.

Converting to array

For any of the types: integer, float, string, boolean and resource, if you convert a value to an array, you get an array with one element (with index 0), which is the scalar value you started with.

If you convert an object to an array, you get the properties (member variables) of that object as the array's elements. The keys are the member variable names.

If you convert a NULL value to an array, you get an empty array.

Comparing

It is possible to compare arrays by array_diff() and by Array operators.

Examples

The array type in PHP is very versatile, so here will be some examples to show you the full power of arrays.

<?php
// this
$a = array( 'color' => 'red',
          
'taste' => 'sweet',
          
'shape' => 'round',
          
'name'  => 'apple',
                      
4        // key will be 0
        
);

// is completely equivalent with
$a['color'] = 'red';
$a['taste'] = 'sweet';
$a['shape'] = 'round';
$a['name']  = 'apple';
$a[]        = 4;        // key will be 0

$b[] = 'a';
$b[] = 'b';
$b[] = 'c';
// will result in the array array(0 => 'a' , 1 => 'b' , 2 => 'c'),
// or simply array('a', 'b', 'c')
?>

Example 11-6. Using array()

<?php
// Array as (property-)map
$map = array( 'version'    => 4,
            
'OS'        => 'Linux',
            
'lang'      => 'english',
            
'short_tags' => true
          
);
          
// strictly numerical keys
$array = array( 7,
              
8,
              
0,
              
156,
               -
10
            
);
// this is the same as array(0 => 7, 1 => 8, ...)

$switching = array(        10, // key = 0
                  
5    =>  6,
                  
3    =>  7,
                  
'a'  =>  4,
                          
11, // key = 6 (maximum of integer-indices was 5)
                  
'8'  =>  2, // key = 8 (integer!)
                  
'02' => 77, // key = '02'
                  
0    => 12  // the value 10 will be overwritten by 12
                
);
                
// empty array
$empty = array();       
?>

Example 11-7. Collection

<?php
$colors
= array('red', 'blue', 'green', 'yellow');

foreach (
$colors as $color) {
   echo
"Do you like $color?\n";
}

?>

The above example will output:

Do you like red?
Do you like blue?
Do you like green?
Do you like yellow?

Note that it is currently not possible to change the values of the array directly in such a loop. A workaround is the following:

Example 11-8. Collection

<?php
foreach ($colors as $key => $color) {
  
// won't work:
   //$color = strtoupper($color);
  
   // works:
  
$colors[$key] = strtoupper($color);
}
print_r($colors);
?>

The above example will output:

Array
(
    [0] => RED
    [1] => BLUE
    [2] => GREEN
    [3] => YELLOW
)

This example creates a one-based array.

Example 11-9. One-based index

<?php
$firstquarter 
= array(1 => 'January', 'February', 'March');
print_r($firstquarter);
?>

The above example will output:

Array 
(
    [1] => 'January'
    [2] => 'February'
    [3] => 'March'
)

Example 11-10. Filling an array

<?php
// fill an array with all items from a directory
$handle = opendir('.');
while (
false !== ($file = readdir($handle))) {
  
$files[] = $file;
}
closedir($handle);
?>

Arrays are ordered. You can also change the order using various sorting functions. See the array functions section for more information. You can count the number of items in an array using the count() function.

Example 11-11. Sorting an array

<?php
sort
($files);
print_r($files);
?>

Because the value of an array can be anything, it can also be another array. This way you can make recursive and multi-dimensional arrays.

Example 11-12. Recursive and multi-dimensional arrays

<?php
$fruits
= array ( "fruits"  => array ( "a" => "orange",
                                      
"b" => "banana",
                                      
"c" => "apple"
                                    
),
                
"numbers" => array ( 1,
                                      
2,
                                      
3,
                                      
4,
                                      
5,
                                      
6
                                    
),
                
"holes"  => array (      "first",
                                      
5 => "second",
                                          
"third"
                                    
)
               );

// Some examples to address values in the array above
echo $fruits["holes"][5];    // prints "second"
echo $fruits["fruits"]["a"]; // prints "orange"
unset($fruits["holes"][0]);  // remove "first"

// Create a new multi-dimensional array
$juices["apple"]["green"] = "good";
?>

You should be aware that array assignment always involves value copying. You need to use the reference operator to copy an array by reference.

<?php
$arr1
= array(2, 3);
$arr2 = $arr1;
$arr2[] = 4; // $arr2 is changed,
             // $arr1 is still array(2, 3)
            
$arr3 = &$arr1;
$arr3[] = 4; // now $arr1 and $arr3 are the same
?>



User Contributed Notes
Arrays
z
22-Apr-2005 02:10
Here's a simple function to insert a value into some position in an array

<?php
function array_insert($array,$pos,$val)
{
  
$array2 = array_splice($array,$pos);
  
$array[] = $val;
  
$array = array_merge($array,$array2);
  
   return
$array;
}
?>

and now for example...
<?php
$a
= array("John","Paul","Peter");
$a = array_insert($a,1,"Mike");
?>

Now $a will be "John","Mike","Paul","Peter"
jeff splat codedread splot com
21-Apr-2005 11:16
Beware that if you're using strings as indices in the $_POST array, that periods are transformed into underscores:

<html>
<body>
<?php
   printf
("POST: "); print_r($_POST); printf("<br/>");
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
   <input type="hidden" name="Windows3.1" value="Sux">
   <input type="submit" value="Click" />
</form>
</body>
</html>

Once you click on the button, the page displays the following:

POST: Array ( [Windows3_1] => Sux )
roland dot swingler at transversal dot com
05-Apr-2005 10:24
Something that tripped me up:

If you mix string and integer keys, be careful if you are doing a comparison on the to find if a string key exists.

For example, this will not do what you expect it to do:

<?php
$exampleArray
= array();
$exampleArray['foo'] = 'bar';
$exampleArray[] = 'Will create 0 index';

$keyWeAreLookingFor = "correctKey";

foreach (
$exampleArray as $key => $value){
  if (
$key == $keyWeAreLookingFor){
   print
"Found Key";
  }
}
?>

It will print "Found Key", because (I presume) when PHP makes the comparison between the string "correctKey" and the index 0, it casts the string to an integer, rather than casting 0 to the string "0" and then doing the comparison.

Using === fixes the problem:

<?php
foreach ($exampleArray as $key => $value){
  if (
$key === $keyWeAreLookingFor){
   print
"Found Key";
  }
}
?>
lars-phpcomments at ukmix dot net
28-Mar-2005 10:40
Used to creating arrays like this in Perl?

@array = ("All", "A".."Z");

Looks like we need the range() function in PHP:

<?php
$array
= array_merge(array('All'), range('A', 'Z'));
?>

You don't need to array_merge if it's just one range:

<?php
$array
= range('A', 'Z');
?>
keystorm at gmail
23-Mar-2005 03:13
In reply to arhipov at donotspam at narod dot ru. This is not a strange behaviour, this is the inbuilt string char index reference:

<?php
$string
= 'Hello';
echo
$string[1]; //This will print 'e' on screen
echo $string['random']; //This will return 'H' since the expected integer index was not found and the string 'random' is int 0 (=> H)
?>
arhipov at donotspam at narod dot ru
21-Mar-2005 05:33
Strange behavior of array
It is found on PHP 4.3.10, 5.0.2

<?php
$test
["a"]=123;
echo
"*".$test["a"]."*".$test["a"]["b"]."*";
?>
This example prints *123**
It is true because $test["a"]["b"] is not assigned

<?php
$test
["a"]="123";
echo
"*".$test["a"]."*".$test["a"]["b"]."*";
?>
This example prints *123*1*
PHP prints first symbol of $test["a"] as value of non-existent element
mortoray at ecircle-ag dot com
16-Feb-2005 02:59
On array copying a deep copy is done of elements except those elements which are references, in which case the reference is maintained.  This is a very important thing to understand if you intend on mixing references and recursive arrays.

By Example:
   $a = array( 1 );
   $aref_a = array( &$a );
   $copy_aref_a = $aref_a;
   $acopy_a = array( $a );
   $copy_acopy_a = $acopy_a;

   $a[] = 5;
   $acopy_a[0][] = 6;

   print_r( $aref_a ); //Shows: ( (1,5) )
   print_r( $copy_aref_a ); //Shows: ( (1,5) )
   print_r( $acopy_a ); //Shows: ( (1, 6) )
   print_r( $copy_acopy_a ); //Shows: ( (1) )
ktaufik(at)gmail(dot)com
16-Feb-2005 02:40
For you who works for localized "say" number to letter ( ex , 7=> seven, 8=>eight) for Bahasa Indonesia.

Indonesia "say" or "Terbilang" is based on 3 digit number.
thousands, millions and trillions .... will be based on the 3 digit number.

In Indonesia you say 137 as "Seratus Tiga Puluh Tujuh"

<?php
//build random 3 digit number to be "said" in Bahasa Indonesia
$x=rand(0,9);
$y=rand(0,9);
$z=rand(0,9);

function
display_angka_bilangan($n) {
  
$angka = array(
    
1 => 'satu',
    
2 => 'dua',
    
3 => 'tiga',
    
4 => 'empat',
    
5 => "lima",
    
6 => 'enam',
    
7 => 'tujuh',
    
8 => 'delapan',
    
9 => 'sembilan'
  
);
   return
$angka[$n];
}
// Terbilang X-------Say X
if ($x==1){$terbilangx="seratus ";}
elseif (
$x==0){$terbilangx='';}
else {
$terbilangx=''.display_angka_bilangan($x).' '.'ratus ';}
// Terbilang Y ------Say Y
if ($y==0){$terbilangy='';}
elseif (
$y==1 && $z==1){$terbilangy="sebelas";$terbilangz='';}
elseif (
$y==1 && $z==0){$terbilangy="sepuluh ";$terbilangz='';}
elseif (
$y==1 && $z!==1 &&  $z!==0){$terbilangy=''.display_angka_bilangan($z).' belas ';}
else {
$terbilangy=''.display_angka_bilangan($y).' '.'puluh ';}
// Terbilang z ------Say z
if ($z==0){$terbilangz="";}
elseif (
$z==0 && $y==1){$terbilangz="";}
elseif (
$z==1 && $y==1){$terbilangz="";}
elseif(
$y==0) {$terbilangz="".display_angka_bilangan($z);}
elseif (
$y==1 && $z!==1 &&  $z!==0) {$terbilangz="";}
else {
$terbilangz="".display_angka_bilangan($z);};

$terbilang=$terbilangx.$terbilangy.$terbilangz;
echo
$x.$y.$z." ";
echo
$terbilang;
?>

Hope it is useful
ktaufik(at)gmail(dot)com
ericchile at hotmail dot comRemoveThis
31-Jan-2005 11:21
Here is an array of states if anyone needs them!

$states = array(
           'AL' => 'Alabama',
           'AK' => 'Alaska',
           'AZ' => 'Arizona',
           'AR' => 'Arkansas',
           'CA' => 'California',
           'CO' => 'Colorado',
           'CT' => 'Connecticut',
           'DE' => 'Delaware',
           'DC' => 'Dist Columbia',
           'FL' => 'Florida',
           'GA' => 'Georgia',
           'HI' => 'Hawaii',
           'ID' => 'Idaho',
           'IL' => 'Illinois',
           'IN' => 'Indiana',
           'IA' => 'Iowa',
           'KS' => 'Kansas',
           'KY' => 'Kentucky',
           'LA' => 'Louisiana',
           'ME' => 'Maine',
           'MD' => 'Maryland',
           'MA' => 'Massachusetts',
           'MI' => 'Michigan',
           'MN' => 'Minnesota',
           'MS' => 'Mississippi',
           'MO' => 'Missouri',
           'MT' => 'Montana',
           'NE' => 'Nebraska',
           'NV' => 'Nevada',
           'NH' => 'New Hampshire',
           'NJ' => 'New Jersey',
           'NM' => 'New Mexico',
           'NY' => 'New York',
           'NC' => 'North Carolina',
           'ND' => 'North Dakota',
           'OH' => 'Ohio',
           'OK' => 'Oklahoma',
           'OR' => 'Oregon',
           'PA' => 'Pennsylvania',
           'RI' => 'Rhode Island',
           'SC' => 'South Carolina',
           'SD' => 'South Dakota',
           'TN' => 'Tennessee',
           'UT' => 'Utah',
           'VT' => 'Vermont',
           'VA' => 'Virginia',
           'WA' => 'Washington',
           'WV' => 'West Virginia',
           'WI' => 'Wisconsin',
           'WY' => 'Wyoming'
           );
jmarbas at hotmail dot com
29-Jan-2005 07:15
response to Sir_Fred

If you print out the two arrays you will see that they are different copies and $arr2 is not a reference to $arr1. If it were referenced then adding an element to $arr2 would also add an element to $arr1. Maybe Im not understanding your comments. Can you give us a sample code that shows = returns a reference?

<?php
  $arr1
= array(2,3);
 
$arr2 = $arr1;
 
print_r($arr1);
 
print_r($arr2);

 
$arr2[] = 4;
 
print_r($arr1);
 
print_r($arr2);
?>
19-Jan-2005 04:04
<?

$array
[-5] = 'minus five';
$array[]  = 'minus four ';
$array[]  = 'minus three';
$array[]  = 'minus two';
$array[]  = 'minus one';
$array[]  = 'zero';
$array[]  = 'one';
$array[]  = 'two';
$array[]  = 'three';
$array[]  = 'four';

echo
"<pre>";
print_r($array);
echo
"</pre>";

?>

result :
Array
(
   [-5] => minus five
   [0] => minus four
   [1] => minus three
   [2] => minus two
   [3] => minus one
   [4] => zero
   [5] => one
   [6] => two
   [7] => three
   [8] => four
)

php verion : 5.02
Gary Smirny <banderon A imyourgod D com>
13-Jan-2005 04:59
In responce to NOcom.gmail@ 's comment:
 
--------------------------------------------------------
I've been trying to create a multidimensional array with an arbitrary depth, but I've run into a snag:
 
<?php
  $array
= Array();
 
$array[1][2][3] = "huzzah!";
 
$string = "[4][5][6]";
  ${
"array" . $string} = "boo!";
 
$array{$string} = "hiss!";
?>

...
 
It seems that no matter what I do, I can't get PHP to treat the string as actual syntax. Has anyone else had any luck with arbitrary-depth arrays? I'm not sure whether or not to call this a bug, nor am I sure if it applies to PHP 5... I've only tested it in 4.3.10.
--------------------------------------------------------
 
What you need to do is use eval() and treat the command as you would a string.  The following code should do what you want:
 
<?php
  $array
= Array();
 
$array[1][2][3] = "huzzah!";
 
$string = "[4][5][6]";
  eval(
'$' . 'array' . $string . ' = "boo!"; ');
 
$array{$string} = "hiss!";
 
 
print_r($array);
?>

That will output:
 
Array
(
   [1] => Array
       (
           [2] => Array
               (
                   [3] => huzzah!
               )
       )
   [4] => Array
       (
           [5] => Array
               (
                   [6] => boo!
               )
       )
   [[4][5][6]] => hiss!
)
 
Hope that helps anyone else having this problem.
db
05-Jan-2005 09:06
Attention with Arrays in Arrays!

If you copy (=) an array which contains arrays it will be REFERENCED not COPIED.

Example:

<?php
/* GOOD ONE */
echo "<b>Here copy (=) works correct:</b><br>";
/* Initialise Array 1 */
$x1 = array(array(10,20),array(30,40));
/* COPY Array */
$x2 = $x1;
/* Change some values in Array 2 */
$x2[0][0]=77;
$x2[1][1]=99;
echo
"<b>Original:</b><pre>";
var_dump($x1);
echo
"</pre><b>Changed Copy:</b><pre>";
var_dump($x2);

/* BAAAAAAAD ONE */
echo "</pre><hr><b>Here copy (=) FAILS:</b><br>";
/* Initialise Array 1 */
$a1[0]->bla[0]->id=10;
$a1[0]->bla[1]->id=20;
$a1[1]->bla[0]->id=30;
$a1[1]->bla[1]->id=40;
/* COPY Array */
$a2 = $a1;
/* Change some values in Array 2 (!) */
$a2[0]->bla[0]->id=77;
$a2[1]->bla[1]->id=99;
echo
"<b>Original:</b><pre>";
var_dump($a1);
echo
"</pre><b>Changed Copy:</b><pre>";
var_dump($a2);
echo
"</pre>";

php?>

The output of $a1 and $a2 will be the same..
Guillaume Beaulieu
30-Dec-2004 12:53
There is no warning nor error if you make something like:

foreach($a as $b => $b) {
   print $b;
}

It is somewhat weird, but in the philosophy of "permit everything" of php.
NOcom.gmail@yuuichiSPAM
23-Dec-2004 07:32
I've been trying to create a multidimensional array with an arbitrary depth, but I've run into a snag:

<?php
  $array
= Array();
 
$array[1][2][3] = "huzzah!";
 
$string = "[4][5][6]";
  ${
"array" . $string} = "boo!";
 
$array{$string} = "hiss!";
?>

. . . outputs:

Array
(
   [1] => Array
       (
           [2] => Array
               (
                   [3] => huzzah!
               )

       )

   [[4][5][6]] => hiss!
)

It seems that no matter what I do, I can't get PHP to treat the string as actual syntax. Has anyone else had any luck with arbitrary-depth arrays? I'm not sure whether or not to call this a bug, nor am I sure if it applies to PHP 5... I've only tested it in 4.3.10.
Joe Morrison <jdm at powerframe dot com>
08-Nov-2004 03:26
Programmers new to PHP may find the following surprising:

<?php

$x
[1] = 'foo';
$x[0] = 'bar';
echo
"Original array:\n";
var_dump($x);

array_pop($x);
echo
"Array after popping last element:\n";
var_dump($x);

?>

The surprise is that element 0 is deleted, not element 1. Apparently the notion of "last element" has more to do with how the array is stored internally than with which element has the highest numeric index. I recently translated a Perl program to PHP and was bitten by this one.

My solution was to identify all the places in my code where I could prove that the array elements were assigned sequentially. In those cases it is safe to use array_pop, array_splice, etc. since the array indices correspond with the array layout. For the other cases, my solution was to write replacements for the built-in array functions such as this one:

<?php

function safe_pop(&$a)
{
  if (!isset(
$a))
   return;

  if (!
is_array($a))
   return;

  if (
count($a) == 0)
   return;

  unset(
$a[max(array_keys($a))]);
}

?>
mwlist atto lanfear dotto com (Marc W)
14-Oct-2004 08:54
It might be worth noting that Maxim Maletsky's comment from 2002 is no longer valid for newer PHP versions (at least 4.3.4 and 5.0.1):

the following code:

$test[-10] = "-10";
$test[-11] = "-11";
$test[] = "i'm expecting a key value of-9";
var_dump($test);

in fact, prints:

array(3) { [-10]=>  string(3) "-10" [-11]=>  string(3) "-11" [0]=>  string(22) "i'm expecting a key value of -9" }

I.e. while negative integers are valid as indices, they don't affect the internal counter for addition of new items, which appears to only be affected by positive integer key values.

Won-kay.
Marc.
Cameron Brown
18-Nov-2003 10:51
Negative and positive array indices have different behavior when it comes to string<->int conversion.  1 and "1" are treated as identical indices, -1 and "-1" are not.  So:

$arr["1"] and $arr[1] refer to the same element.
$arr["-1"] and $arr[-1] refer to different elements.

The following code:

<?
  $arr
[1]    = "blue";
 
$arr["1"]  = "red";
 
$arr[-1]  = "blue";
 
$arr["-1"] = "red";

 
var_dump($arr);
?>

produces the output:

array(3) {
  [1]=>
  string(3) "red"
  [-1]=>
  string(4) "blue"
  ["-1"]=>
  string(3) "red"
}

This code should create an array with either two or four elements.  Which one should be the "correct" behavior is an exercise left to the reader....
plyrvt at mail dot ru (Yura Pylypenko)
22-Aug-2003 11:57
In documentation it actually states that you can use strings as an array keys, but it was new for me that this can be _any string_ and not only "word" characters are allowed. It is OK to use (for parser, not for your application consistence)
$arr['Any "string" or, even (%), punctuation! Heh?']='This is cool';
akamai at veloxmail dot com dot br
16-Jul-2003 06:22
It is quite simple, but don't forget when you'll using foreach with forms arrays.

If your field name is:
<input type="checkbox" name="foo['bar'][]" ...
It doesn't work.

This should work:
<input type="checkbox" name="foo[bar][]" ...
agape_logos at shaw dot ca
11-Jul-2003 06:59
I was having trouble getting javascript arrays and php arrays to work together with a Check All checkboxe.  Here is a simple solution.  Clicking the 'Check All' checkbox will check all checkboxes on the form.

<script language="JavaScript">
function chkAll(frm, arr, mark) {
  for (i = 0; i <= frm.elements.length; i++) {
   try{
     if(frm.elements[i].name == arr) {
       frm.elements[i].checked = mark;
     }
   } catch(er) {}
  }
}
</script>

<form name='foo'>
<input type="checkbox" name="ca" value="1" onClick="chkAll(this.form, 'formVar[chkValue][]', this.checked)">
<?php
for($i = 0; $i < 5; $i++){
echo(
"<input type='checkbox' name='formVar[chkValue][]' value='$i'>");
}
?>
</form>

Dean M.
chroniton .at. gmx .dot. li
26-Mar-2003 12:13
I didn't find this anywhere in the docs and i think it is worth a mention:

$a[] = &$a;
print_r($a);

// will output:

/*
Array
(
   [0] => Array
 *RECURSION*
)

*/

// this means that $a[0] is a reference to $a ( that is detected by print_r() ). I guess this is what the manual calls 'recursive arrays'.
07-Mar-2003 05:28
"Using NULL as a key will evaluate to an empty string. Using an emptry string as key will create (or overwrite) a key with an empty string and its value, it is not the same as using empty brackets."

If you create an array like this:
$foo = array(null => 'bar');
And then want to access 'bar', you must use this syntax:
echo $foo['']; // notice the two single quotes

This will of course cause a fatal error:
echo $foo[];
wmoranATpotentialtechDOTcom
29-Nov-2002 05:10
Dereferencing arrays takes some time, but is not terribly expensive.
I wrote two dummy loops to test performance:
for ($i =0; $i < count($a); $i++) {
 $x = $a[$b[$i]];
 $y = $a[$b[$i]];
 $z = $a[$b[$i]];
}
for ($i =0; $i < count($a); $i++) {
 $q = $b[$i];
 $x = $a[$q];
 $y = $a[$q];
 $z = $a[$q];
}

The first loop is 6.5% slower than the second.  Meaning that dereferencing arrays is not terribly expensive, unless you do it a whole lot. I would expect that each extra reference costs about 3% in speed. The lesson is that if you're going to be using a specific value in an array for a number of operations, you can gain a little speed by assigning it to a temp variable (or creating a reference with $q = &$b[$i]) but it's not worth getting crazy over.
I tested this with iterations of 10,000 and 100,000 on php 4.2 and the results were consistent.
18-Oct-2002 12:57
Why array-style names won't work with Javascript is actually quite logical. If you take:

<input type="text" name="Settings[Name]">

as an example, then this JavaScript code:

document.forms.FormNameHere.elements.Settings[Name].value

won't work, of course! Name is an undefined constant in this case, as it's interpreted as a constant, not as a string... But adding quotes won't help you:

document.forms.FormNameHere.elements.Settings["Name"].value

Since the name="Settings[Name]" in the tag won't result in a "Settings"-subarray of the form.FormNameHere.elements array in the DOM.

The solution? Use this:

document.forms.FormNameHere.elements["Settings[Name]"].value

"Settings[Name]" is looked up in the elements array, and is found... The elements array is a hash, so strings can be used as keys!
mu at despammed dot com
15-Oct-2002 01:50
Recursive arrays and multi-dimensional arrays are the same thing and completely identical.

The following confirms this:

$fruits1["european"]["green"] = "Apple";
$fruits2 = array ( "european"  => array ( "green" => "Apple"));
print ($fruits1 === $fruits2);

Result: 1 (= true)
maxim at php dot net
20-Jun-2002 12:58
"A key is either a nonnegative integer or a string..."

This is incorrect. If you try this code:

<?

$array
[-5] = 'minus five';
$array[]  = 'minus four ';
$array[]  = 'minus three';
$array[]  = 'minus two';
$array[]  = 'minus one';
$array[]  = 'zero';
$array[]  = 'one';
$array[]  = 'two';
$array[]  = 'three';
$array[]  = 'four';

echo
"<pre>";
print_r($array);
echo
"</pre>";

?>

the result would be:

Array
(
   [-5] => minus five
   [-4] => minus four
   [-3] => minus three
   [-2] => minus two
   [-1] => minus one
   [0] => zero
   [1] => one
   [2] => two
   [3] => three
   [4] => four
)

I will fix this in the documentation.

Maxim Maletsky,
maxim@php.net
hramrach_L at centrum. cz ;-)
11-Jun-2002 07:40
Arrays can be merged using + as discussed in the notes for array_merge.
 http://www.php.net/manual/en/function.array-merge.php
Markus dot Elfring at web dot de
30-May-2002 05:04
It seems to me that the use of brackets with multidimensional arrays is not described here.

But the following examples work:
$value = $point['x']['y'];
$message[1][2][3] = 'Greetings';
philip at boone dot at
24-May-2002 08:06
For all of you having problems when using php arrays in an HTML form input field name, and wanting to validate the form using javascript for example, it is much easier to specify an id for the field as well, and use this id for validation.

Example:

<input type="text" id="lastname" name="fields[lastname]">

then in the javascript check:

if(formname.lastname.value == "") {
     alert("please enter a lastname!");
}

This works very well. If you have any problems with it, let me know.
mjp at pilcrow dot madison dot wi dot us
21-Feb-2000 04:18
Those with a perl background may be surprised to learn that the 'thick arrow' and comma operators are not synonymous in array construction.

For example, the following are equivalent:

$ary = array("foo" => "bar", 1, 2);
$ary = array("foo" => "bar", 0 => 1, 1 => 2);

<StringsObjects>
 Last updated: Thu, 19 May 2005
Copyright © 2001-2005 The PHP Group
All rights reserved.
This unofficial mirror is operated at: The Server Pages
Last updated: Thu May 19 17:35:34 2005 CDT