Array Functions
Arrays
These functions allow you to interact with and manipulate
arrays in various ways. Arrays are essential for storing,
managing, and operating on sets of variables.
Simple and multi-dimensional arrays are supported, and may be
either user created or created by another function.
There are specific database handling functions for populating
arrays from database queries, and several functions return arrays.
See also is_array, explode,
implode, split
and join.
array
Create an array
Description
array array
mixed
...
Returns an array of the parameters. The parameters can be given
an index with the => operator.
Array is a language construct used to
represent literal arrays, and not a regular function.
Syntax "index => values", separated by commas, define index
and values. index may be of type string or numeric. When index is
omitted, a integer index is automatically generated, starting
at 0. If index is an integer, next generated index will
be the biggest integer index + 1. Note that when two identical
index are defined, the last overwrite the first.
The following example demonstrates how to create a
two-dimensional array, how to specify keys for associative
arrays, and how to skip-and-continue numeric indices in normal
arrays.
Array example
$fruits = array (
"fruits" => array ("a"=>"orange", "b"=>"banana", "c"=>"apple"),
"numbers" => array (1, 2, 3, 4, 5, 6),
"holes" => array ("first", 5 => "second", "third")
);
Automatic index with Array
$array = array( 1, 1, 1, 1, 1, 8=>1, 4=>1, 19, 3=>13);
print_r($array);
which will display :
Array
(
[0] => 1
[1] => 1
[2] => 1
[3] => 13
[4] => 1
[8] => 1
[9] => 19
)
Note that index '3' is defined twice, and keep its final value of 13.
Index 4 is defined after index 8, and next generated index (value 19)
is 9, since biggest index was 8.
This example creates a 1-based array.
1-based index with Array
$firstquarter = array(1 => 'January', 'February', 'March');
print_r($firstquarter);
which will display :
Array
(
[1] => 'January'
[2] => 'February'
[3] => 'March'
)
See also: list.
array_count_values
Counts all the values of an array
Description
array array_count_values
array input
Array_count_values returns an array using
the values of the input array as keys and
their frequency in input as values.
Array_count_values example
$array = array (1, "hello", 1, "world", "hello");
array_count_values ($array); // returns array (1=>2, "hello"=>2, "world"=>1)
array_diff
Computes the difference of arrays
Description
array array_diff
array array1
array array2
array
...
Array_diff returns an array
containing all the values of array1
that are not present in any of the other arguments.
Note that keys are preserved.
Array_diff example
$array1 = array ("a" => "green", "red", "blue");
$array2 = array ("b" => "green", "yellow", "red");
$result = array_diff ($array1, $array2);
This makes $result have array
("blue");
See also array_intersect.
array_filter
Filters elements of an array using a callback function
Description
array array_filter
array input
mixed
callback
Array_filter returns an array
containing all the elements of input
filtered according a callback function. If the
input is an associative array
the keys are preserved.
Array_filter example
function odd($var) {
return ($var % 2 == 1);
}
function even($var) {
return ($var % 2 == 0);
}
$array1 = array ("a"=>1, "b"=>2, "c"=>3, "d"=>4, "e"=>5);
$array2 = array (6, 7, 8, 9, 10, 11, 12);
$odd_arr = array_filter($array1, "odd");
$even_arr = array_filter($array2, "even");
This makes $odd_arr have
array ("a"=>1, "c"=>3, "e"=>5);,
and $even_arr have
array (6, 8, 10, 12);,
See also array_map,
array_reduce.
array_flip
Flip all the values of an array
Description
array array_flip
array trans
Array_flip returns an array in flip order.
Array_flip example
$trans = array_flip ($trans);
$original = strtr ($str, $trans);
array_intersect
Computes the intersection of arrays
Description
array array_intersect
array array1
array array2
array
...
Array_intersect returns an array
containing all the values of array1
that are present in all the arguments.
Note that keys are preserved.
Array_intersect example
$array1 = array ("a" => "green", "red", "blue");
$array2 = array ("b" => "green", "yellow", "red");
$result = array_intersect ($array1, $array2);
This makes $result have array ("a"
=> "green", "red");
See also array_diff.
array_keys
Return all the keys of an array
Description
array array_keys
array input
mixed
search_value
Array_keys returns the keys, numeric and
string, from the input array.
If the optional search_value is specified,
then only the keys for that value are returned. Otherwise, all
the keys from the input are returned.
Array_keys example
$array = array (0 => 100, "color" => "red");
array_keys ($array); // returns array (0, "color")
$array = array ("blue", "red", "green", "blue", "blue");
array_keys ($array, "blue"); // returns array (0, 3, 4)
$array = array ("color" => array("blue", "red", "green"), "size" => array("small", "medium", "large"));
array_keys ($array); // returns array ("color", "size")
This function was added to PHP 4, below is an implementation for
those still using PHP 3.
Implementation of array_keys for PHP 3
users
function array_keys ($arr, $term="") {
$t = array();
while (list($k,$v) = each($arr)) {
if ($term && $v != $term)
continue;
$t[] = $k;
}
return $t;
}
See also array_values.
array_map
Applies the callback to the elements of the given arrays
Description
array array_map
mixed callback
array arr1
array
arr2...
Array_map returns an array
containing all the elements of arr1
after applying the callback function to each one.
The number of parameters that the callback function accepts should
match the number of arrays passed to the array_map
Array_map example
function cube($n) {
return $n*$n*$n;
}
$a = array(1, 2, 3, 4, 5);
$b = array_map("cube", $a);
This will result in $b containing
array (1, 8, 27, 64, 125);
Array_map - using more arrays
function show_Spanish($n, $m) {
return "The number $n is called $m in Spanish";
}
function map_Spanish($n, $m) {
return array ($n => $m);
}
$a = array(1, 2, 3, 4, 5);
$b = array("uno", "dos", "tres", "cuatro", "cinco");
$c = array_map("show_Spanish", $a, $b);
print_r($c);
// will output:
// Array
// (
// [0] => The number 1 is called uno in Spanish
// [1] => The number 2 is called dos in Spanish
// [2] => The number 3 is called tres in Spanish
// [3] => The number 4 is called cuatro in Spanish
// [4] => The number 5 is called cinco in Spanish
// )
$d = array_map("map_Spanish", $a , $b);
print_r($d);
// will output:
// Array
// (
// [0] => Array
// (
// [1] => uno
// )
//
// [1] => Array
// (
// [2] => dos
// )
//
// [2] => Array
// (
// [3] => tres
// )
//
// [3] => Array
// (
// [4] => cuatro
// )
//
// [4] => Array
// (
// [5] => cinco
// )
//
// )
Usually when using two or more arrays, they should be of equal length
because the callback function is applied in parallel to the corresponding
elements.
If the arrays are of unequal length, the shortest one will be extended
with empty elements.
An interesting use of this function is to construct an array of arrays,
which can be easily performed by using null
as the name of the callback function
Array_map - creating an array of arrays
$a = array(1, 2, 3, 4, 5);
$b = array("one", "two", "three", "four", "five");
$c = array("uno", "dos", "tres", "cuatro", "cinco");
$d = array_map(null, $a, $b, $c);
print_r($d);
// will output:
// Array
// (
// [0] => Array
// (
// [0] => 1
// [1] => one
// [2] => uno
// )
//
// [1] => Array
// (
// [0] => 2
// [1] => two
// [2] => dos
// )
//
// [2] => Array
// (
// [0] => 3
// [1] => three
// [2] => tres
// )
//
// [3] => Array
// (
// [0] => 4
// [1] => four
// [2] => cuatro
// )
//
// [4] => Array
// (
// [0] => 5
// [1] => five
// [2] => cinco
// )
//
// )
See also array_filter,
array_reduce.
array_merge
Merge two or more arrays
Description
array array_merge
array array1
array array2
array
...
Array_merge merges the elements of two or
more arrays together so that the values of one are appended to
the end of the previous one. It returns the resulting array.
If the input arrays have the same string keys, then the later
value for that key will overwrite the previous one. If, however,
the arrays have the same numeric key, the later value will not
overwrite the original value, but will be appended.
array_merge example
$array1 = array ("color" => "red", 2, 4);
$array2 = array ("a", "b", "color" => "green", "shape" => "trapezoid", 4);
array_merge ($array1, $array2);
Resulting array will be array("color" => "green", 2, 4,
"a", "b", "shape" => "trapezoid", 4).
See also array_merge_recursive.
array_merge_recursive
Merge two or more arrays recursively
Description
array array_merge_recursive
array array1
array array2
array
...
Array_merge_recursive merges the elements of
two or more arrays together so that the values of one are appended
to the end of the previous one. It returns the resulting array.
If the input arrays have the same string keys, then the values for
these keys are merged together into an array, and this is done
recursively, so that if one of the values is an array itself, the
function will merge it with a corresponding entry in another array
too. If, however, the arrays have the same numeric key, the later
value will not overwrite the original value, but will be appended.
Array_merge_recursive example
$ar1 = array ("color" => array ("favorite" => "red"), 5);
$ar2 = array (10, "color" => array ("favorite" => "green", "blue"));
$result = array_merge_recursive ($ar1, $ar2);
Resulting array will be array ("color" => array
("favorite" => array ("red", "green"), "blue"), 5, 10).
See also array_merge.
array_multisort
Sort multiple or multi-dimensional arrays
Description
bool array_multisort
array ar1
mixed
arg
mixed
...
array
...
Array_multisort can be used to sort several
arrays at once or a multi-dimensional array according by one of
more dimensions. It maintains key association when sorting.
The input arrays are treated as columns of a table to be sorted
by rows - this resembles the functionality of SQL ORDER BY
clause. The first array is the primary one to sort by. The rows
(values) in that array that compare the same are sorted by the
next input array, and so on.
The argument structure of this function is a bit unusual, but
flexible. The very first argument has to be an
array. Subsequently, each argument can be either an array or a
sorting flag from the following lists.
Sorting order flags:
SORT_ASC - sort in ascending order
SORT_DESC - sort in descending order
Sorting type flags:
SORT_REGULAR - compare items normally
SORT_NUMERIC - compare items numerically
SORT_STRING - compare items as strings
No two sorting flags of the same type can be specified after each
array. The sortings flags specified after an array argument apply
only to that array - they are reset to default SORT_ASC and
SORT_REGULAR after before each new array argument.
Returns TRUE on success, FALSE
on failure.
Sorting multiple arrays
$ar1 = array ("10", 100, 100, "a");
$ar2 = array (1, 3, "2", 1);
array_multisort ($ar1, $ar2);
In this example, after sorting, the first array will contain 10,
"a", 100, 100. The second array will contain 1, 1, 2, "3". The
entries in the second array corresponding to the identical
entries in the first array (100 and 100) were sorted as well.
Sorting multi-dimensional array
$ar = array (array ("10", 100, 100, "a"), array (1, 3, "2", 1));
array_multisort ($ar[0], SORT_ASC, SORT_STRING,
$ar[1], SORT_NUMERIC, SORT_DESC);
In this example, after sorting, the first array will contain 10,
100, 100, "a" (it was sorted as strings in ascending order), and
the second one will contain 1, 3, "2", 1 (sorted as numbers, in
descending order).
array_pad
Pad array to the specified length with a value
Description
array array_pad
array input
int pad_size
mixed pad_value
Array_pad returns a copy of the
input padded to size specified by
pad_size with value
pad_value. If
pad_size is positive then the array is
padded on the right, if it's negative then on the left. If the
absolute value of pad_size is less than or
equal to the length of the input then no
padding takes place.
Array_pad example
$input = array (12, 10, 9);
$result = array_pad ($input, 5, 0);
// result is array (12, 10, 9, 0, 0)
$result = array_pad ($input, -7, -1);
// result is array (-1, -1, -1, -1, 12, 10, 9)
$result = array_pad ($input, 2, "noop");
// not padded
array_pop
Pop the element off the end of array
Description
mixed array_pop
array array
Array_pop pops and returns the last value of
the array, shortening the
array by one element.
If array is empty (or is not an array),
NULL will be returned.
Array_pop example
$stack = array ("orange", "apple", "raspberry");
$fruit = array_pop ($stack);
After this, $stack has only 2 elements:
"orange" and "apple", and $fruit has
"raspberry".
See also array_push,
array_shift, and
array_unshift.
array_push
Push one or more elements onto the end of array
Description
int array_push
array array
mixed var
mixed
...
Array_push treats
array as a stack, and pushes the passed
variables onto the end of array. The
length of array increases by the number of
variables pushed. Has the same effect as:
$array[] = $var;
repeated for each var.
Returns the new number of elements in the array.
Array_push example
$stack = array (1, 2);
array_push ($stack, "+", 3);
This example would result in $stack having 4
elements: 1, 2, "+", and 3.
See also: array_pop,
array_shift, and
array_unshift.
array_rand
Pick one or more random entries out of an array
Description
mixed array_rand
array input
int
num_req
Array_rand is rather useful when you want to
pick one or more random entries out of an array. It takes an
input array and an optional argument
num_req which specifies how many entries you
want to pick - if not specified, it defaults to 1.
If you are picking only one entry, array_rand
returns the key for a random entry. Otherwise, it returns an array
of keys for the random entries. This is done so that you can pick
random keys as well as values out of the array.
Don't forget to call srand to seed the random
number generator.
Array_rand example
srand ((double) microtime() * 10000000);
$input = array ("Neo", "Morpheus", "Trinity", "Cypher", "Tank");
$rand_keys = array_rand ($input, 2);
print $input[$rand_keys[0]]."\n";
print $input[$rand_keys[1]]."\n";
array_reverse
Return an array with elements in reverse order
Description
array array_reverse
array array
bool preserve_keys
Array_reverse takes input
array and returns a new array with the
order of the elements reversed, preserving the keys if
preserve_keys is TRUE.
Array_reverse example
$input = array ("php", 4.0, array ("green", "red"));
$result = array_reverse ($input);
$result_keyed = array_reverse ($input, TRUE);
This makes $result have array
(array ("green", "red"), 4.0, "php"). But
$result2[0] is still
"php".
The second parameter was added in PHP 4.0.3.
array_reduce
Iteratively reduce the array to a single value using a callback function
Description
mixed array_reduce
array input
mixed callback
int
initial
Array_reduce applies iteratively the
callback function to the elements of the
array input, so as to reduce the array to
a single value. If the optional intial is
avaliable, it will be used at the beginning of the process, or as
a final result in case the array is empty.
Array_reduce example
function rsum($v, $w) {
$v += $w;
return $v;
}
function rmul($v, $w) {
$v *= $w;
return $v;
}
$a = array(1, 2, 3, 4, 5);
$x = array();
$b = array_reduce($a, "rsum");
$c = array_reduce($a, "rmul", 10);
$d = array_reduce($x, "rsum", 1);
This will result in $b containing
15, $c containing
1200 (= 1*2*3*4*5*10), and $d
containing 1.
See also array_filter,
array_map.
array_shift
Pop an element off the beginning of array
Description
mixed array_shift
array array
Array_shift shifts the first value of the
array off and returns it, shortening the
array by one element and moving everything
down.
If array is empty (or is not an array),
NULL will be returned.
Array_shift example
$args = array ("-v", "-f");
$opt = array_shift ($args);
This would result in $args having one element
"-f" left, and $opt being "-v".
See also array_unshift,
array_push, and
array_pop.
array_slice
Extract a slice of the array
Description
array array_slice
array array
int offset
int
length
Array_slice returns a sequence of elements
from the array specified by the
offset and length
parameters.
If offset is positive, the sequence will
start at that offset in the array. If
offset is negative, the sequence will
start that far from the end of the array.
If length is given and is positive, then
the sequence will have that many elements in it. If
length is given and is negative then the
sequence will stop that many elements from the end of the
array. If it is omitted, then the sequence will have everything
from offset up until the end of the
array.
Array_slice examples
$input = array ("a", "b", "c", "d", "e");
$output = array_slice ($input, 2); // returns "c", "d", and "e"
$output = array_slice ($input, 2, -1); // returns "c", "d"
$output = array_slice ($input, -2, 1); // returns "d"
$output = array_slice ($input, 0, 3); // returns "a", "b", and "c"
See also array_splice.
array_splice
Remove a portion of the array and replace it with something
else
Description
array array_splice
array input
int offset
int
length
array
replacement
Array_splice removes the elements designated
by offset and
length from the
input array, and replaces them with the
elements of the replacement array, if
supplied.
If offset is positive then the start of
removed portion is at that offset from the beginning of the
input array. If
offset is negative then it starts that far
from the end of the input array.
If length is omitted, removes everything
from offset to the end of the array. If
length is specified and is positive, then
that many elements will be removed. If
length is specified and is negative then
the end of the removed portion will be that many elements from
the end of the array. Tip: to remove everything from
offset to the end of the array when
replacement is also specified, use
count($input) for
length.
If replacement array is specified, then
the removed elements are replaced with elements from this array.
If offset and
length are such that nothing is removed,
then the elements from the replacement
array are inserted in the place specified by the
offset. Tip: if the replacement is just
one element it is not necessary to put array()
around it, unless the element is an array itself.
The following equivalences hold:
array_push ($input, $x, $y) array_splice ($input, count ($input), 0,
array ($x, $y))
array_pop ($input) array_splice ($input, -1)
array_shift ($input) array_splice ($input, 0, 1)
array_unshift ($input, $x, $y) array_splice ($input, 0, 0, array ($x, $y))
$a[$x] = $y array_splice ($input, $x, 1, $y)
Returns the array consisting of removed elements.
Array_splice examples
$input = array ("red", "green", "blue", "yellow");
array_splice ($input, 2); // $input is now array ("red", "green")
array_splice ($input, 1, -1); // $input is now array ("red", "yellow")
array_splice ($input, 1, count($input), "orange");
// $input is now array ("red", "orange")
array_splice ($input, -1, 1, array("black", "maroon"));
// $input is now array ("red", "green",
// "blue", "black", "maroon")
See also array_slice.
array_sum
Calculate the sum of values in an array.
Description
mixed array_sum
array arr
Array_sum returns the sum of values
in an array as an integer or float.
Array_sum examples
$a = array(2,4,6,8);
echo "sum(a) = ".array_sum($a)."\n";
// prints: sum(a) = 20
$b = array("a"=>1.2,"b"=>2.3,"c"=>3.4);
echo "sum(b) = ".array_sum($b)."\n";
// prints: sum(b) = 6.9
array_unique
Removes duplicate values from an array
Description
array array_unique
array array
Array_unique takes input
array and returns a new array
without duplicate values.
Note that keys are preserved.
Array_unique example
$input = array ("a" => "green", "red", "b" => "green", "blue", "red");
$result = array_unique ($input);
This makes $result have array ("a" =>
"green", "red", "blue");.
array_unshift
Push one or more elements onto the beginning of array
Description
int array_unshift
array array
mixed var
mixed
...
Array_unshift prepends passed elements to
the front of the array. Note that the list
of elements is prepended as a whole, so that the prepended
elements stay in the same order.
Returns the new number of elements in the
array.
Array_unshift example
$queue = array ("p1", "p3");
array_unshift ($queue, "p4", "p5", "p6");
This would result in $queue having 5
elements: "p4", "p5", "p6", "p1", and "p3".
See also array_shift,
array_push, and
array_pop.
array_values
Return all the values of an array
Description
array array_values
array input
array_values returns all the values from the
input array.
Array_values example
$array = array ("size" => "XL", "color" => "gold");
array_values ($array); // returns array ("XL", "gold")
This function was added to PHP 4, below is an implementation for
those still using PHP 3.
Implementation of array_values for PHP 3
users
function array_values ($arr) {
$t = array();
while (list($k, $v) = each ($arr)) {
$t[] = $v;
}
return $t;
}
array_walk
Apply a user function to every member of an array
Description
int array_walk
array arr
string func
mixed userdata
Applies the function named by func to each
element of arr.
func will be passed array value as the
first parameter and array key as the second parameter. If
userdata is supplied, it will be passed as
the third parameter to the user function.
If func requires more than two or three
arguments, depending on userdata, a
warning will be generated each time
array_walk calls
func. These warnings may be suppressed by
prepending the '@' sign to the array_walk
call, or by using error_reporting.
If func needs to be working with the
actual values of the array, specify that the first parameter of
func should be passed by reference. Then
any changes made to those elements will be made in the array
itself.
Passing the key and userdata to func was
added in 4.0.
In PHP 4 reset needs to be called as
necessary since array_walk does not reset
the array by default.
Array_walk example
$fruits = array ("d"=>"lemon", "a"=>"orange", "b"=>"banana", "c"=>"apple");
function test_alter (&$item1, $key, $prefix) {
$item1 = "$prefix: $item1";
}
function test_print ($item2, $key) {
echo "$key. $item2<br>\n";
}
array_walk ($fruits, 'test_print');
reset ($fruits);
array_walk ($fruits, 'test_alter', 'fruit');
reset ($fruits);
array_walk ($fruits, 'test_print');
See also each and list.
arsort
Sort an array in reverse order and maintain index association
Description
void arsort
array array
int
sort_flags
This function sorts an array such that array indices maintain
their correlation with the array elements they are associated
with. This is used mainly when sorting associative arrays where
the actual element order is significant.
Arsort example
$fruits = array ("d"=>"lemon", "a"=>"orange", "b"=>"banana", "c"=>"apple");
arsort ($fruits);
reset ($fruits);
while (list ($key, $val) = each ($fruits)) {
echo "$key = $val\n";
}
This example would display:
fruits[a] = orange
fruits[d] = lemon
fruits[b] = banana
fruits[c] = apple
The fruits have been sorted in reverse alphabetical order, and
the index associated with each element has been maintained.
You may modify the behavior of the sort using the optional
parameter sort_flags, for details
see sort.
See also: asort, rsort,
ksort, and sort.
asort
Sort an array and maintain index association
Description
void asort
array array
int sort_flags
This function sorts an array such that array indices maintain
their correlation with the array elements they are associated
with. This is used mainly when sorting associative arrays where
the actual element order is significant.
Asort example
$fruits = array ("d"=>"lemon", "a"=>"orange", "b"=>"banana", "c"=>"apple");
asort ($fruits);
reset ($fruits);
while (list ($key, $val) = each ($fruits)) {
echo "$key = $val\n";
}
This example would display:
fruits[c] = apple
fruits[b] = banana
fruits[d] = lemon
fruits[a] = orange
The fruits have been sorted in alphabetical order, and the index
associated with each element has been maintained.
You may modify the behavior of the sort using the optional
parameter sort_flags, for details
see sort.
See also arsort, rsort,
ksort, and sort.
compact
Create array containing variables and their values
Description
array compact
mixed varname
mixed
...
Compact takes a variable number of
parameters. Each parameter can be either a string containing the
name of the variable, or an array of variable names. The array
can contain other arrays of variable names inside it;
compact handles it recursively.
For each of these, compact looks for a
variable with that name in the current symbol table and adds it
to the output array such that the variable name becomes the key
and the contents of the variable become the value for that key.
In short, it does the opposite of extract.
It returns the output array with all the variables added to it.
Any strings that are not set will simply be skipped.
Compact example
$city = "San Francisco";
$state = "CA";
$event = "SIGGRAPH";
$location_vars = array ("city", "state");
$result = compact ("event", "nothing_here", $location_vars);
After this, $result will be array ("event"
=> "SIGGRAPH", "city" => "San Francisco", "state" => "CA").
See also extract.
count
Count elements in a variable
Description
int count
mixed var
Returns the number of elements in var,
which is typically an array (since anything else will have one
element).
Returns 1 if the variable is not an array.
Returns 0 if the variable is not set.
Count may return 0 for a variable that
isn't set, but it may also return 0 for a variable that has
been initialized with an empty array. Use
isset to test if a variable is set.
Count example
$a[0] = 1;
$a[1] = 3;
$a[2] = 5;
$result = count ($a);
//$result == 3
See also: sizeof,
isset, and
is_array.
current
Return the current element in an array
Description
mixed current
array array
Every array has an internal pointer to its "current" element,
which is initialized to the first element inserted into the
array.
The current function simply returns the
array element that's 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.
If the array contains empty elements (0 or "", the empty
string) then this function will return FALSE
for these elements as well. This makes it impossible to
determine if you are really at the end of the list in such
an array using current. To properly
traverse an array that may contain empty elements, use the
each function.
See also: end, next,
prev, and reset.
each
Return the next key and value pair from an array
Description
array each
array array
Returns the current key and value pair from the array
array and advances the array cursor. This
pair is returned in a four-element array, with the keys
0, 1,
key, and
value. Elements 0 and
key contain the key name of the array
element, and 1 and
value contain the data.
If the internal pointer for the array points past the end of the
array contents, each returns
FALSE.
Each examples
$foo = array ("bob", "fred", "jussi", "jouni", "egon", "marliese");
$bar = each ($foo);
$bar now contains the following key/value
pairs:
0 => 0
1 => 'bob'
key => 0
value => 'bob'
$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'
Each is typically used in conjunction with
list to traverse an array; for instance,
$HTTP_POST_VARS:
Traversing $HTTP_POST_VARS with
each
echo "Values submitted via POST method:<br>";
reset ($HTTP_POST_VARS);
while (list ($key, $val) = each ($HTTP_POST_VARS)) {
echo "$key => $val<br>";
}
After each has executed, the array cursor
will be left on the next element of the array, or on the last
element if it hits the end of the array.
See also key, list,
current, reset,
next, and prev.
end
Set the internal pointer of an array to its last element
Description
mixed end
array array
End advances array's
internal pointer to the last element, and returns that element.
See also: current,
each, end,
next, and reset.
in_array
Return TRUE if a value exists in an array
Description
bool in_array
mixed needle
array haystack
bool
strict
Searches haystack for
needle and returns TRUE
if it is found in the array, FALSE otherwise.
If the third parameter strict is set to
TRUE then the in_array
will also check the types of the needle
in the haystack.
In_array example
$os = array ("Mac", "NT", "Irix", "Linux");
if (in_array ("Irix", $os)){
print "Got Irix";
}
In_array with strict example
// This will output:
1.13 found with strict check
See also array_search.
array_search
Searches the array for a given value and returns the corresponding key if successful
Description
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 third parameter strict is set to
TRUE then the array_search
will also check the types of the needle
in the haystack.
See also in_array.
key
Fetch a key from an associative array
Description
mixed key
array array
Key returns the index element of the
current array position.
See also current and next.
krsort
Sort an array by key in reverse order
Description
int krsort
array array
int
sort_flags
Sorts an array by key in reverse order, maintaining key to data
correlations. This is useful mainly for associative arrays.
Krsort example
$fruits = array ("d"=>"lemon", "a"=>"orange", "b"=>"banana", "c"=>"apple");
krsort ($fruits);
reset ($fruits);
while (list ($key, $val) = each ($fruits)) {
echo "$key -> $val\n";
}
This example would display:
fruits[d] = lemon
fruits[c] = apple
fruits[b] = banana
fruits[a] = orange
You may modify the behavior of the sort using the optional
parameter sort_flags, for details
see sort.
See also asort, arsort,
ksort sort,
natsortand rsort.
ksort
Sort an array by key
Description
int ksort
array array
int
sort_flags
Sorts an array by key, maintaining key to data correlations. This
is useful mainly for associative arrays.
Ksort example
$fruits = array ("d"=>"lemon", "a"=>"orange", "b"=>"banana", "c"=>"apple");
ksort ($fruits);
reset ($fruits);
while (list ($key, $val) = each ($fruits)) {
echo "$key -> $val\n";
}
This example would display:
fruits[a] = orange
fruits[b] = banana
fruits[c] = apple
fruits[d] = lemon
You may modify the behavior of the sort using the optional
parameter sort_flags, for details
see sort.
See also asort, arsort,
sort, natsort, and
rsort.
The second parameter was added in PHP 4.
list
Assign variables as if they were an array
Description
void list
Like array, this is not really a function,
but a language construct. list is used to
assign a list of variables in one operation.
List example
<table>
<tr>
<th>Employee name</th>
<th>Salary</th>
</tr>
<?php
$result = mysql_query ($conn, "SELECT id, name, salary FROM employees");
while (list ($id, $name, $salary) = mysql_fetch_row ($result)) {
print (" <tr>\n".
" <td><a href=\"info.php3?id=$id\">$name</a></td>\n".
" <td>$salary</td>\n".
" </tr>\n");
}
?>
</table>
See also each and array.
natsort
Sort an array using a "natural order" algorithm
Description
void natsort
array array
This function implements a sort algorithm that orders
alphanumeric strings in the way a human being would. This is
described as a "natural ordering". An example of the difference
between this algorithm and the regular computer string sorting
algorithms (used in sort) can be seen below:
natsort example
$array1 = $array2 = array ("img12.png","img10.png","img2.png","img1.png");
sort($array1);
echo "Standard sorting\n";
print_r($array1);
natsort($array2);
echo "\nNatural order sorting\n";
print_r($array2);
The code above will generate the following output:
Standard sorting
Array
(
[0] => img1.png
[1] => img10.png
[2] => img12.png
[3] => img2.png
)
Natural order sorting
Array
(
[3] => img1.png
[2] => img2.png
[1] => img10.png
[0] => img12.png
)
For more infomation see: Martin Pool's Natural Order String Comparison
page.
See also natcasesort,
strnatcmp and
strnatcasecmp.
natcasesort
Sort an array using a case insensitive "natural order" algorithm
Description
void natcasesort
array array
This function implements a sort algorithm that orders
alphanumeric strings in the way a human being would. This is
described as a "natural ordering".
natcasesort is a case insensitive version of
natsort. See natsort
for an example of the difference between this algorithm and the
regular computer string sorting algorithms.
For more infomation see: Martin Pool's Natural Order String Comparison
page.
See also sort,
natsort,
strnatcmp and
strnatcasecmp.
next
Advance the internal array pointer of an array
Description
mixed next
array array
Returns the array element in the next place that's pointed by the
internal array pointer, or FALSE if
there are no more elements.
Next behaves like
current, with one difference. It advances
the internal array pointer one place forward before returning the
element. That means it returns the next array element and
advances the internal array pointer by one. If advancing the
internal array pointer results in going beyond the end of the
element list, next returns FALSE.
If the array contains empty elements, or elements that have a key
value of 0 then this function will return FALSE
for these elements as well. To properly traverse an array which
may contain empty elements or elements with key values of 0 see the
each function.
See also:
current, end,
prev, and reset.
pos
Get the current element from an array
Description
mixed pos
array array
This is an alias for current.
See also:
end, next,
prev and reset.
prev
Rewind the internal array pointer
Description
mixed prev
array array
Returns the array element in the previous place that's pointed by
the internal array pointer, or FALSE if there are no more
elements.
If the array contains empty elements then this function will
return FALSE for these elements as well.
To properly traverse an array which may contain empty elements
see the each function.
Prev behaves just like
next, except it rewinds the internal array
pointer one place instead of advancing it.
See also: current, end,
next, and reset.
range
Create an array containing a range of integers
Description
array range
int low
int high
Range returns an array of integers from
low to high,
inclusive.
See shuffle for an example of its use.
reset
Set the internal pointer of an array to its first element
Description
mixed reset
array array
Reset rewinds array's
internal pointer to the first element.
Reset returns the value of the first array
element.
See also: current,
each, next,
and prev.
rsort
Sort an array in reverse order
Description
void rsort
array array
int
sort_flags
This function sorts an array in reverse order (highest to lowest).
Rsort example
$fruits = array ("lemon", "orange", "banana", "apple");
rsort ($fruits);
reset ($fruits);
while (list ($key, $val) = each ($fruits)) {
echo "$key -> $val\n";
}
This example would display:
fruits[0] = orange
fruits[1] = lemon
fruits[2] = banana
fruits[3] = apple
The fruits have been sorted in reverse alphabetical order.
You may modify the behavior of the sort using the optional
parameter sort_flags, for details
see sort.
See also: arsort,
asort, ksort,
sort, and usort.
shuffle
Shuffle an array
Description
void shuffle
array array
This function shuffles (randomizes the order of the elements in)
an array. You must use srand to seed this
function.
Shuffle example
$numbers = range (1,20);
srand ((double)microtime()*1000000);
shuffle ($numbers);
while (list (, $number) = each ($numbers)) {
echo "$number ";
}
See also arsort, asort,
ksort, rsort,
sort and usort.
sizeof
Get the number of elements in an array
Description
int sizeof
array array
Returns the number of elements in the array.
See also count.
sort
Sort an array
Description
void sort
array array
int sort_flags
This function sorts an array. Elements will be arranged from
lowest to highest when this function has completed.
Sort example
<?php
$fruits = array ("lemon", "orange", "banana", "apple");
sort ($fruits);
reset ($fruits);
while (list ($key, $val) = each ($fruits)) {
echo "fruits[".$key."] = ".$val;
}
?>
This example would display:
fruits[0] = apple
fruits[1] = banana
fruits[2] = lemon
fruits[3] = orange
The fruits have been sorted in alphabetical order.
The optional second parameter sort_flags
may be used to modify the sorting behavior using theese valies:
Sorting type flags:
SORT_REGULAR - compare items normally
SORT_NUMERIC - compare items numerically
SORT_STRING - compare items as strings
See also: arsort,
asort, ksort,
natsort, natcasesort,
rsort, usort,
array_multisort, and uksort.
The second parameter was added in PHP 4.
uasort
Sort an array with a user-defined comparison function and
maintain index association
Description
void uasort
array array
function cmp_function
This function sorts an array such that array indices maintain
their correlation with the array elements they are associated
with. This is used mainly when sorting associative arrays where
the actual element order is significant. The comparison function
is user-defined.
Please see usort and
uksort for examples of user-defined
comparison functions.
See also: usort, uksort,
sort, asort,
arsort, ksort
and rsort.
uksort
Sort an array by keys using a user-defined comparison function
Description
void uksort
array array
function cmp_function
This function will sort the keys of an array using a
user-supplied comparison function. If the array you wish to sort
needs to be sorted by some non-trivial criteria, you should use
this function.
Uksort example
function cmp ($a, $b) {
if ($a == $b) return 0;
return ($a > $b) ? -1 : 1;
}
$a = array (4 => "four", 3 => "three", 20 => "twenty", 10 => "ten");
uksort ($a, "cmp");
while (list ($key, $value) = each ($a)) {
echo "$key: $value\n";
}
This example would display:
20: twenty
10: ten
4: four
3: three
See also: usort, uasort,
sort, asort,
arsort, ksort,
natsort and rsort.
usort
Sort an array by values using a user-defined comparison function
Description
void usort
array array
string cmp_function
This function will sort an array by its values using a
user-supplied comparison function. If the array you wish to sort
needs to be sorted by some non-trivial criteria, you should use
this 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.
Usort 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\n";
}
This example would display:
0: 6
1: 5
2: 3
3: 2
4: 1
Obviously in this trivial case the rsort
function would be more appropriate.
Usort example using multi-dimensional array
function cmp ($a, $b) {
return strcmp($a["fruit"],$b["fruit"]);
}
$fruits[0]["fruit"] = "lemons";
$fruits[1]["fruit"] = "apples";
$fruits[2]["fruit"] = "grapes";
usort($fruits, "cmp");
while (list ($key, $value) = each ($fruits)) {
echo "\$fruits[$key]: " . $value["fruit"] . "\n";
}
When sorting a multi-dimensional array, $a and $b contain
references to the first index of the array.
This example would display:
$fruits[0]: apples
$fruits[1]: grapes
$fruits[2]: lemons
The underlying quicksort function in some C libraries (such as
on Solaris systems) may cause PHP to crash if the comparison
function does not return consistent values.
See also: uasort, uksort,
sort, asort,
arsort,ksort,
natsort, and rsort.