PHP » PYTHON |
login |
register |
about
|
|
ArraysAn 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 by the array() language construct. It takes as parameters any number of comma-separated key => value pairs. array( key => value , ... ) // key may only be an integer or string // value may be any value of any type
<?phpA 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. The indexed and associative array types are the same type in PHP, which can both contain integer and string indices. A value can be any PHP type.
<?phpIf a key is not specified for a value, the maximum of the integer indices is taken and the new key will be that value plus 1. If a key that already has an assigned value is specified, that value will be overwritten.
<?phpWarning
Before PHP 4.3.0, appending to an array in which the current maximum key was negative would create a new key as described above. Since PHP 4.3.0, the new key will be 0. Using TRUE as key will evaluate to integer 1 as a key. Using FALSE as key will evaluate to integer 0 as a key. Using NULL as a key will evaluate to the empty string. Using the empty string as a key will create (or overwrite) a key with the empty string and its value; it is not the same as using empty brackets. Arrays and objects can not be used as keys. Doing so will result in a warning: Illegal offset type. 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 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. 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
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:
<?phpThis is wrong, but it works. The reason is that this code has an undefined constant (bar) rather than a string ('bar' - notice the quotes). PHP may in future define constants which, unfortunately for such 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.
More examples to demonstrate this behaviour:
<?phpWhen 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:
<?phpThis is an example of using a function return value as the array index. PHP also knows about constants:
<?phpNote 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:
<?phpbecause 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: 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:
<?phpThe above will appear to have two keys named 'AA', although one of them is actually named '\0A\0A'. ComparingIt is possible to compare arrays with the array_diff() function and with array operators. ExamplesThe array type in PHP is very versatile. Here are some examples:
<?phpExample #1 Using array()
<?phpExample #2 Collection
<?phpThe 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 since PHP 5 by passing them by reference. Before that, a workaround is necessary: Example #3 Collection
<?phpThe above example will output:
Array
(
[0] => RED
[1] => BLUE
[2] => GREEN
[3] => YELLOW
)
This example creates a one-based array. Example #4 One-based index
<?phpThe above example will output:
Array
(
[1] => 'January'
[2] => 'February'
[3] => 'March'
)
Example #5 Filling an array
<?phpArrays 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 #6 Sorting an array
<?phpBecause 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 #7 Recursive and multi-dimensional arrays
<?phpArray assignment always involves value copying. Use the reference operator to copy an array by reference.
<?php |
more
Recently updated
more
Most requested
|