An array in PHP is actually an ordered map. A map is a type that associates values to keys. This type is optimized for several different uses; it can be treated as an array, list (vector), hash table (an implementation of a map), dictionary, collection, stack, queue, and probably more. As array values can be other arrays, trees and multidimensional arrays are also possible. Explanation of those data structures is beyond the scope of this manual, but at least one example is provided for each of them. For more information, look towards the considerable literature that exists about this broad topic. SyntaxSpecifying with array()An array can be created using the array() language construct. It takes any number of comma-separated key => value pairs as arguments. array( key => value, key2 => value2, key3 => value3, ... )The comma after the last array element is optional and can be omitted. This is usually done for single-line arrays, i.e. array(1, 2) is preferred over array(1, 2, ). For multi-line arrays on the other hand the trailing comma is commonly used, as it allows easier addition of new elements at the end.
Example #1 A simple array <?php The key can either be an int or a string. The value can be of any type. Additionally the following key casts will occur:
If multiple elements in the array declaration use the same key, only the last one will be used as all others are overwritten. Example #2 Type Casting and Overwriting example <?php The above example will output: array(1) { [1]=> string(1) "d" } As all the keys in the above example are cast to 1, the value will be overwritten on every new element and the last assigned value "d" is the only one left over. PHP arrays can contain int and string keys at the same time as PHP does not distinguish between indexed and associative arrays. Example #3 Mixed int and string keys <?php The above example will output: array(4) { ["foo"]=> string(3) "bar" ["bar"]=> string(3) "foo" [100]=> int(-100) [-100]=> int(100) } The key is optional. If it is not specified, PHP will use the increment of the largest previously used int key. Example #4 Indexed arrays without key <?php The above example will output: array(4) { [0]=> string(3) "foo" [1]=> string(3) "bar" [2]=> string(5) "hello" [3]=> string(5) "world" } It is possible to specify the key only for some elements and leave it out for others: Example #5 Keys not on all elements <?php The above example will output: array(4) { [0]=> string(1) "a" [1]=> string(1) "b" [6]=> string(1) "c" [7]=> string(1) "d" } As you can see the last value "d" was assigned the key 7. This is because the largest integer key before that was 6. Example #6 Complex Type Casting and Overwriting example This example includes all variations of type casting of keys and overwriting of elements. <?php The above example will output: array(7) { [1]=> string(1) "g" [-1]=> string(1) "d" ["01"]=> string(1) "e" ["1.5"]=> string(1) "f" [0]=> string(1) "h" [""]=> string(1) "j" [2]=> string(1) "l" } Accessing array elements with square bracket syntaxArray elements can be accessed using the array[key] syntax. Example #7 Accessing array elements <?php The above example will output: string(3) "bar" int(24) string(3) "foo"
Example #8 Array dereferencing <?php
Creating/modifying with square bracket syntaxAn existing array can be modified by explicitly setting values in it. This is done by assigning values to the array, specifying the key in brackets. The key can also be omitted, resulting in an empty pair of brackets ([]). $arr[key] = value; $arr[] = value; // key may be an int or string // value may be any value of any typeIf $arr doesn't exist yet or is set to null or false, it will be created, so this is also an alternative way to create an array. This practice is however discouraged because if $arr already contains some value (e.g. string from request variable) then this value will stay in the place and [] may actually stand for string access operator. It is always better to initialize a variable by a direct assignment.
To change a certain value, assign a new value to that element using its key. To remove a key/value pair, call the unset() function on it. <?php
Array destructuringArrays can be destructured using the [] (as of PHP 7.1.0) or list() language constructs. These constructs can be used to destructure an array into distinct variables. <?php [ $foo, $bar, $baz] = $source_array;echo $foo; // prints "foo"echo $bar; // prints "bar" echo $baz; // prints "baz" ?> Array destructuring can be used in foreach to destructure a multi-dimensional array while iterating over it. <?php foreach ( $source_array as [$id, $name]) {// logic here with $id and $name } ?> Array elements will be ignored if the variable is not provided. Array destructuring always starts at index 0. <?php echo $baz; // prints "baz"?> As of PHP 7.1.0, associative arrays can be destructured too. This also allows for easier selection of the right element in numerically indexed arrays as the index can be explicitly specified. <?php echo $three; // prints 3$source_array = ['foo', 'bar', 'baz'];// Assign the element at index 2 to the variable $baz[2 => $baz] = $source_array; echo $baz; // prints "baz"?> Array destructuring can be used for easy swapping of two variables. <?php [ $b, $a] = [$a, $b];echo $a; // prints 2echo $b; // prints 1 ?>
Useful functionsThere are quite a few useful functions for working with arrays. See the array functions section.
The foreach control structure exists specifically for arrays. It provides an easy way to traverse an array. Array do's and don'tsWhy is $foo[bar] wrong?Always use quotes around a string literal array index. For example, $foo['bar'] is correct, while $foo[bar] is not. But why? It is common to encounter this kind of syntax in old scripts: <?php This is wrong, but it works. The reason is that this code has an undefined constant (bar) rather than a string ('bar' - notice the quotes). 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. Warning The fallback to treat an undefined constant as bare string issues an error of level E_NOTICE. This has been deprecated as of PHP 7.2.0, and issues an error of level E_WARNING. As of PHP 8.0.0, it has been removed and throws an Error exception.
More examples to demonstrate this behaviour: <?php // Incorrect. This works but also throws a PHP error of level E_NOTICE because // This defines a constant to demonstrate what's going on. The value 'veggie' print $arr['fruit']; // apple print $arr[fruit]; // carrot // The following is okay, as it's inside a string. Constants are not looked for // With one exception: braces surrounding arrays within strings allows constants print "Hello {$arr['fruit']}"; // Hello apple // This will not work, and will result in a parse error, such as: print "Hello $_GET['foo']";// Concatenation is another option print "Hello " . $arr['fruit']; // Hello apple ?> When error_reporting is set to show E_NOTICE level errors (by setting it to E_ALL, for example), such uses will become immediately visible. By default, error_reporting is set not to show notices. As stated in the syntax section, what's inside the square brackets ('[' and ']') must be an expression. This means that code like this works: <?php This is an example of using a function return value as the array index. PHP also knows about constants: <?php 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 because E_ERROR equals 1, etc. So why is it bad then?At some point in the future, the PHP team might want to add another constant or keyword, or a constant in other code may interfere. For example, it is already wrong to use the words empty and default this way, since they are reserved keywords.
Converting to arrayFor any of the types int, float, string, bool and resource, converting a value to an array results in an array with a single element with index zero and the value of the scalar which was converted. In other words, (array)$scalarValue is exactly the same as array($scalarValue). If an object is converted to an array, the result is an array whose elements are the object's properties. The keys are the member variable names, with a few notable exceptions: integer properties are unaccessible; private variables have the class name prepended to the variable name; protected variables have a '*' prepended to the variable name. These prepended values have NUL bytes on either side. Uninitialized typed properties are silently discarded. <?phpclass A { The above example will output: array ( '' . "\0" . 'A' . "\0" . 'B' => NULL, '' . "\0" . '*' . "\0" . 'C' => NULL, 'D' => NULL, 1 => NULL, ) These NUL can result in some unexpected behaviour: <?phpclass A { class B extends A {private $A; // This will become '\0B\0A' public $AA; // This will become 'AA' }var_dump((array) new B()); ?> The above example will output: array(3) { ["BA"]=> NULL ["AA"]=> NULL ["AA"]=> NULL } The above will appear to have two keys named 'AA', although one of them is actually named '\0A\0A'. Converting null to an array results in an empty array. Array unpackingAn array prefixed by ... will be expanded in place during the definition of the array. Only arrays and objects which implement Traversable can be expanded. Array unpacking with ... is available as of PHP 7.4.0. It's possible to expand multiple times, and add normal elements before or after the ... operator: Example #9 Simple array unpacking <?php Unpacking an array with the ... operator follows the semantics of the array_merge() function. That is, later string keys overwrite earlier ones and integer keys are renumbered: Example #10 Array unpacking with duplicate key <?php // integer key $arr4 = [1, 2, 3];$arr5 = [4, 5, 6]; $arr6 = [...$arr4, ...$arr5]; var_dump($arr6); // [1, 2, 3, 4, 5, 6] // Which is [0 => 1, 1 => 2, 2 => 3, 3 => 4, 4 => 5, 5 => 6] // where the original integer keys have not been retained. ?>
ExamplesThe array type in PHP is very versatile. Here are some examples: <?php Example #11 Using array() <?php Example #12 Collection <?php 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? Changing the values of the array directly is possible by passing them by reference. Example #13 Changing element in the loop <?php The above example will output: Array ( [0] => RED [1] => BLUE [2] => GREEN [3] => YELLOW ) This example creates a one-based array. Example #14 One-based index <?php The above example will output: Array ( [1] => 'January' [2] => 'February' [3] => 'March' ) Example #15 Filling an array <?php Arrays are ordered. The order can be changed using various sorting functions. See the array functions section for more information. The count() function can be used to count the number of items in an array. Example #16 Sorting an array <?php Because the value of an array can be anything, it can also be another array. This enables the creation of recursive and multi-dimensional arrays. Example #17 Recursive and multi-dimensional arrays <?php // Create a new multi-dimensional array $juices["apple"]["green"] = "good";?> Array assignment always involves value copying. Use the reference operator to copy an array by reference. <?php thomas tulinsky ¶ 6 years ago I think your first, main example is needlessly confusing, very confusing to newbies: $array = array( It should be removed. For newbies: The following expressions are both true: liberchen at gmail dot com ¶ 4 years ago Since PHP 7.1, the string will not be converted to array automatically. Below codes will fail: $a=array(); You have to change to as below: $a=array(); $a['a']=array(); // Declare it is an array first ken underscore yap atsign email dot com ¶ 14 years ago "If you convert a NULL value to an array, you get an empty array." This turns out to be a useful property. Say you have a search function that returns an array of values on success or NULL if nothing found. <?php $values =
search(...); ?> <?php $combined = array_merge((array)$values, $other); ?> jeff splat codedread splot com ¶ 17 years ago Beware that if you're using strings as indices in the $_POST array, that periods are transformed into underscores: <html> Once you click on the button, the page displays the following: POST: Array ( [Windows3_1] => Sux ) Yesterday php'er ¶ 5 years ago
--- quote --- At least for php 5.4 and 5.6; if function returns an array, the curly brackets does not work directly accessing function result, eg. WillReturnArray(){1} . This will give "syntax error, unexpected '{' in...". chris at ocportal dot com ¶ 9 years ago Note that array value buckets are reference-safe, even through serialization. <?php ia [AT] zoznam [DOT] sk ¶ 16 years ago Regarding the previous comment, beware of the fact that reference to the last value of the array remains stored in $value after the foreach: <?php Bad results can also appear in nested foreach loops (the same reason as above). So either unset $value after each foreach or better use the longer form: <?php anisgazig at gmail dot com ¶ 3 years ago //array keys are always integer and string data type and array values are all data type //NOte :array and object data type in keys are Illegal ofset....... caifara aaaat im dooaat be ¶ 17 years ago [Editor's note: You can achieve what you're looking for by referencing $single, rather than copying it by value in your foreach statement. See http://php.net/foreach for more details.] Don't know if this is known or not, but it did eat some of my time and maybe it won't eat your time now... I tried to add something to a multidimensional array, but that didn't work at first, look at the code below to see what I mean: <?php $a1 = array( "a" => 0, "b" => 1 );$a2 = array( "aa" => 00, "bb" => 11 ); $together = array( $a1, $a2 ); foreach( $together as $single ) {$single[ "c" ] = 3 ; } print_r( $together ); /* nothing changed result is: Array ( [0] => Array ( [a] => 0 [b] => 1 ) [1] => Array ( [aa] => 0 [bb] => 11 ) ) */ foreach( $together as $key => $value ) { $together[$key]["c"] = 3 ; } print_r( $together ); /* now it works, this prints Array ( [0] => Array ( [a] => 0 [b] => 1 [c] => 3 ) [1] => Array ( [aa] => 0 [bb] => 11 [c] => 3 ) ) */ ?> dylanfj700 at gmail dot com ¶ 2 years ago // Before php 5.4 // since php 5.4 , short syntax // I recommend using the short syntax if you have php version >= 5.4 lars-phpcomments at ukmix dot net ¶ 17 years ago Used to creating arrays like this in Perl? @array = ("All", "A".."Z"); Looks like we need the range() function in PHP: <?php <?php ivail89 at mail dot ru ¶ 1 year ago Function unset can delete array's element by reference only when you specify source array. See example: Or different example: note dot php dot lorriman at spamgourmet dot org ¶ 8 years ago There is another kind of array (php>= 5.3.0) produced by $array = new SplFixedArray(5); Standard arrays, as documented here, are marvellously flexible and, due to the underlying hashtable, extremely fast for certain kinds of lookup operation. Supposing a large string-keyed array $arr=['string1'=>$data1, 'string2'=>$data2 etc....] when getting the keyed data with $data=$arr['string1']; php does *not* have to search through the array comparing each key string to the given key ('string1') one by one, which could take a long time with a large array. Instead the hashtable means that php takes the given key string and computes from it the memory location of the keyed data, and then instantly retrieves the data. Marvellous! And so quick. And no need to know anything about hashtables as it's all hidden away. However, there is a lot of overhead in that. It uses lots of memory, as hashtables tend to (also nearly doubling on a 64bit server), and should be significantly slower for integer keyed arrays than old-fashioned (non-hashtable) integer-keyed arrays. For that see more on SplFixedArray : http://uk3.php.net/SplFixedArray Unlike a standard php (hashtabled) array, if you lookup by integer then the integer itself denotes the memory location of the data, no hashtable computation on the integer key needed. This is much quicker. It's also quicker to build the array compared to the complex operations needed for hashtables. And it uses a lot less memory as there is no hashtable data structure. This is really an optimisation decision, but in some cases of large integer keyed arrays it may significantly reduce server memory and increase performance (including the avoiding of expensive memory deallocation of hashtable arrays at the exiting of the script). phplatino at gmail dot com ¶ 1 year ago to know the depth (dimension) of a ARRAY, you can use this: function Dim_Ar($A, $i){ and use with: $Q = ARRAY(ARRAY(ARRAY()), ARRAY(ARRAY()));// here depth/dimension is three echo Dim_Ar($Q, 0); tissus ¶ 4 years ago In array(key=>value) construct key is also an expression. Denise Ignatova ¶ 4 years ago When creating arrays , if we have an element with the same value as another element from the same array, we would expect PHP instead of creating new zval container to increase the refcount and point the duplicate symbol to
the same zval. This is true except for value type integer. $arr = ['bebe' => 'Bob', 'age' => 23, 'too' => 23 ]; Output: (refcount=2, is_ref=0) but : will produce: (refcount=2, is_ref=0) $arr = ['bebe' => 'Bob', 'age' => [1,2], 'too' => [1,2] ]; Output: (refcount=2, is_ref=0) ivegner at yandex dot ru ¶ 9 years ago Note that objects of classes extending ArrayObject SPL class are treated as arrays, and not as objects when converting to array. <?php Walter Tross ¶ 12 years ago It is true that "array assignment always involves value copying", but the copy is a "lazy copy". This means that the data of the two variables occupy the same memory as long as no array element changes. E.g., if you have to pass an array to a function that only needs to read it, there is no advantage at all in passing it by reference. Anonymous ¶ 2 years ago Wrappers for (array), returns array with normalize keys (without prefix): function to_array($value): array{ $arr = (array) $value; if (! is_object($value)) { return $arr; } $class = get_class($value); $keys = str_replace(["\0*\0", "\0{$class}\0"], '', array_keys($arr)); return array_combine($keys, $arr); } ?> Demo: <?php class Test { protected $var = 1; protected $var2; private $TestVar = 3; public function __construct($isParent = true){ if ($isParent) { $this->var2 = new self(! $isParent); } } }$obj = new Test(); var_dump((array) $obj, to_array_recursive($obj)); ?> |