Arrays

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.

Syntax

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.

As of PHP 5.4 you can also use the short array syntax, which replaces
array() with [].

Example #1 A simple array

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

// as of PHP 5.4$array = ["foo" => "bar","bar" => "foo",];?>

The key can either be an integer
or a string. The value can be
of any type.

Additionally the following key casts will occur:

Strings containing valid decimal integers, unless the number is preceded by a + sign, will be cast to the
integer type. E.g. the key "8" will actually be
stored under 8. On the other hand "08" will
not be cast, as it isn't a valid decimal integer.

Floats are also cast to integers, which means that the
fractional part will be truncated. E.g. the key 8.7 will actually
be stored under 8.

Bools are cast to integers, too, i.e. the key
true will actually be stored under 1
and the key false under 0.

Null will be cast to the empty string, i.e. the key
null will actually be stored under "".

Arrays and objects can not be used as keys.
Doing so will result in a warning: Illegal offset type.

If multiple elements in the array declaration use the same key, only the last one
will be used as all others are overwritten.

Creating/modifying with square bracket syntax

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 integer or string
// value may be any value of any type

If $arr doesn't exist yet, 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.

Note:
As of PHP 7.1.0, applying the empty index operator on a string throws a fatal
error. Formerly, the string was silently converted to an array.

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$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 no key is specified, the maximum of the existing
integer indices is taken, and the new key will be that maximum
value plus 1 (but at least 0). If no integer indices exist yet, the key will
be 0 (zero).

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

Useful functions

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

Note:

The unset() function allows removing keys from an
array. Be aware that the array will not be
reindexed. If a true "remove and shift" behavior is desired, the
array can be reindexed using the
array_values() function.

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?

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$foo[bar] = 'enemy';echo $foo[bar];// etc?>

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.

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

// 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

// This defines a constant to demonstrate what's going on. The value 'veggie'// is assigned to a constant named fruit.define('fruit', 'veggie');

// This will not work, and will result 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 superglobals in strings as wellprint "Hello $arr['fruit']";print "Hello $_GET['foo']";

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.

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,
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 null bytes on either side. This can result in some
unexpected behaviour:

<?php

class A { private $A; // This will become '\0A\0A'}

class B extends A { private $A; // This will become '\0B\0A'public $AA; // This will become 'AA'}

var_dump((array) new B());?>

The above will appear to have two keys named 'AA', although one of them is
actually named '\0A\0A'.

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 #13 Sorting an array

<?phpsort($files);print_r($files);?>

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.

This, in my point of view, should be cast to an array type and throw the same error.

This is, according to the documentation on this page, wrong.

From doc:"Note:Attempting to access an array key which has not been defined is the same as accessing any other undefined variable: an E_NOTICE-level error message will be issued, and the result will be NULL."

--- quote ---Note:Both square brackets and curly braces can be used interchangeably for accessing array elements--- quote end ---

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...".Personally I use only square brackets, expect for accessing single char in string. Old habits...

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 :

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).

This, in my point of view, should be cast to an array type and throw the same error.

This is, according to the documentation on this page, wrong.

From doc:"Note:Attempting to access an array key which has not been defined is the same as accessing any other undefined variable: an E_NOTICE-level error message will be issued, and the result will be NULL.""

$a['a'] is not an array. It is null. That rule does not applyInstead $a['b'] is an array. Rule is applied.

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.

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. Example:

This page should include details about how associative arrays are implemened inside PHP; e.g. using hash-maps or b-trees.

This has important implictions on the permance characteristics of associative arrays and how they should be used; e.g. b-tree are slow to insert but handle collisions better than hashmaps. Hashmaps are faster if there are no collisions, but are slower to retrieve when there are collisions. These factors have implictions on how associative arrays should be used.

The print_r() will display *RECURSION* when it gets to the third element of the array.

There doesn't appear to be any other way to scan an array for recursive references, so if you need to check for them, you'll have to use print_r() with its second parameter to capture the output and look for the word *RECURSION*.

It's not an elegant solution, but it's the only one I've found, so I hope it helps someone.

Its worth noting that there does not appear to be any functional limitations on the length or content of string indexes. The string indexes for your arrays can contain any characters, including new line characters, and can be of any length:

Keep in mind that using extremely long array indexes is not a good practice and could cost you lots of extra CPU time. However, if you have to use a long string as an array index you won't have to worry about the length or content.