Contents / Previous / Next


Arrays

An array in PHP is actually an ordered map. A map is a type that maps values to keys.
An array can be created by the array() language-construct: array( [key =>] value , ... ) Key is either string (associative array) or nonnegative integer, the value can be anything.
Example: $tree = array("trunk", "branches", "leaves"); Is completely equivalent with: $tree = array( 0 => "trunk", 1 => "branches", 2 => "leaves"); You can also create arrays with the square-bracket syntax: $arr[] = value; Example: $tree[]="trunk"; $tree[]="branches"; $tree[]="leaves"; In both cases the value: tree[0] evaluates to the string "trunk".
In this way arrays may be dynamically expanded.

You can make the array start at any number (the default is 0):

$arr[key] = value; Example: $tree[7]="trunk"; $tree[2]="branches"; $tree[8]="leaves"; If $arr does not exist yet, it will be created.
In this case tree[0] would be empty.

This syntax is also used to modify and access an existing array:

$tree[2]="apple"; $my_fruit = $tree[2];

If you want to remove a key/value pair, you need to unset() it: Destroy a single element of an array:

unset ($tree['leaves']); Destroy a single variable and a complete array you man destroy more than one variable at a time: unset ($my_fruit, $tree); If a globalized variable is unset() inside of a function, only the local variable is destroyed. The variable in the calling environment will retain the same value as before unset() was called.
If you would like to unset() a global variable inside of a function, you can use the $GLOBALS array to do so:


Associative Arrays

In associative arrays the keys are not integers but strings. $aFruit = array( 'color' => 'red' , 'taste' => 'sweet' , 'shape' => 'round' , 'name' => 'apple' , 4 // key will be 0 ); Is equivalent with: $aFruit['color'] = 'red'; $aFruit['taste'] = 'sweet'; $aFruit['shape'] = 'round'; $aFruit['name'] = 'apple'; $aFruit[] = 4; // key will be 0 You can access and modify an array element value with the key string: $aFruit ['color'] = 'green';


Multi-Dimensional and Recursive Arrays

Multi-dimensional arrays are created as follows: $everything = array ( "fruits" => array ( "a" => "orange", "b" => "banana", "c" => "apple" ), "numbers" => array ( 1, 2, 3 ), "holes" => array ( "first", "second" ) ); The array elements can be accessed like: echo $everything["fruits"]["c"]; //an "apple".

Because the value of an array can be everything, it can also be another array. This way you can produce "recursive arrays".


Array Pointer: current(), end(), next(), and reset()

Every array has an internal pointer. It is initialized to the first element inserted into the array.

current() returns the array element that is currently being pointed by the internal pointer. It does not move the pointer in any way. If the internal pointer points beyond the end of the elements list, current() returns FALSE.

next()/prev() advances/rewinds the internal array pointer by one place before returning the element. It returns FALSE if there are no more elements.

reset()/end() Set the internal pointer of the array to its first/last element.

key() returns the key (index) element of the current array position.


each(), key() and list()

each() returns the current key and value pair from the array and advances the array cursor: current_value_pair each (array) This pair is returned in a four-element array. Elements 0 and key contain the key name of the array element, and 1 and value contain the data. Example: $foo = array ("Robert" => "Bob", "Seppo" => "Sepi"); $bar = each ($foo); $bar now contains the following key/value pairs: * 0 => 'Robert' * 1 => 'Bob' * key => 'Robert' * value => 'Bob' reset( $foo ); while( $bar = each ($foo) ) print " ".$bar[0]."=>".$bar[1];

list() is used to assign a list of variables in one operation. list() is like array() not really a function, but a language construct. Example:

$tree = array("trunk", "branches", "leaves"); list( $wood1, $wood2 ) = $tree; This is equivalent to: $woo1 = $tree[0]; $woo2 = $tree[1];

each() is often used in conjunction with list() to traverse an array; for instance, $HTTP_POST_VARS (values submitted from a HTML-form via POST method):

reset ($HTTP_POST_VARS); while (list ($key, $val) = each ($HTTP_POST_VARS)) { echo "$key => $val<br>"; }


Array Functions

is_array(): Returns TRUE if var is an array, FALSE otherwise.

in_array(): Return TRUE if a value exists in an array.


Printing

Printing can be done with a foreach loop or with the print_r() function. Try: foreach( $aFruit as $a ) print("$a "); print_r($aFruit);


explode(): Split a string into array elements

Returns an array of strings, each of which is a substring of string formed by splitting it on boundaries formed by the string separator: array explode (string separator, string string [, int limit]) If limit is set, the returned array will contain a maximum of limit elements with the last element containing the whole rest of string.
Example: $pizza = "piece1 piece2 piece3 piece4 piece5 piece6"; $pieces = explode (" ", $pizza);


join() = implode(): Join array elements to a string

Returns a string containing a string representation of all the array elements in the same order, with the glue string between each element: string implode (string glue, array pieces)


Search

The array_search function searches an array for a given value and returns the corresponding key if successful.

mixed array_search ( mixed needle, array haystack [, bool strict]):
Searches haystack for needle and returns the key if it is found in the array, FALSE otherwise.
If the optional third parameter strict is set to TRUE then the array_search() will also check the types of the needle in the haystack.


Sorting Arrays

The sort() function sorts an array: void sort (array array [, int sort_flags]) Elements will be arranged from lowest to highest:
The optional second parameter sort_flags may be used to modify the sorting behavior using these values:

usort() sort an array by values using a user-defined comparison function:

void usort (array array, string cmp_function) The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second. If two members compare as equal, their order in the sorted array is undefined.
Example: function cmp ($a, $b) { if ($a == $b) return 0; return ($a < $b) ? -1 : 1; } $a = array (3, 2, 5, 6, 1); usort ($a, "cmp"); while (list ($key, $value) = each ($a)) { echo "$key: $value<BR>"; }

Other sorting functions are: arsort(), asort(), ksort(), natsort(), natcasesort(), rsort(), usort(), array_multisort(), and uksort().


Other Array Functions (Ref-Table at php.net)

PHP provides numerous functions for Arrays, and you are referred to the Manual for all of these.