Some Array-Related Functions
Approximately 60 array-related functions are built into PHP, which you can read about in detail at http://www.php.net/array. Some of the more common (and useful) functions are explained in this section.
- count() and sizeof()
Each counts the number of elements in an array. Given the following array:
both count($colors); and sizeof($colors); return a value of 4.
$colors = array("blue", "black", "red", "green"); - each() and list()
These usually appear together, in the context of stepping through an array and returning its keys and values. The following example steps through an associative array called $character, printing its key, the text has a value of, and the value, followed by an HTML break.
while (list($key, $val) = each($characater)) {
echo "$key has a value of $val <br>";
} - foreach()
This is also used to step through an array, assigning the value of an element to a given variable. The following example steps through an associative array called $character, prints some text, the value, and finally an HTML break.
foreach($characater as $c) {
echo "The value is $c <br>";
} - reset()
This rewinds the pointer to the beginning an array, as in this example:
This function is useful when you are performing multiple manipulations on an array, such as sorting, extracting values, and so forth.
reset($character); - array_push()
This adds one or more elements to the end of an existing array, as in this example:
array_push($existingArray, "element 1", "element 2", "element 3"); - array_pop()
This removes (and returns) the last element of an existing array, as in this example:
$last_element = array_pop($existingArray); - array_unshift()
This adds one or more elements to the beginning of an existing array, as in this example:
array_unshift($existingArray, "element 1", "element 2", "element 3"); - array_shift()
This removes (and returns) the first element of an existing array, as in this example:
$first_element = array_shift($existingArray); - array_merge()
This combines two or more existing arrays, as in this example:
$newArray = array_merge($array1, $array2); - array_keys()
This returns an array containing all the key names within a given array, as in this example:
$keysArray = array_keys($existingArray); - array_values()
This returns an array containing all the values within a given array, as in this example:
$valuesArray = array_values($existingArray); - shuffle()
This randomizes the elements of a given array. The syntax of this function is simply as follows:
shuffle($existingArray);
This brief rundown of array-related functions only scratches the surface of using arrays. However, arrays and array-related functions are used in the code examples throughout this book.