Array FunctionsArrays
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.
Please see the Arrays
section of the manual for a detailed explanation of how arrays are
implemented and used in PHP.
See also is_array, explode,
implode, split
and join.
array
Create an array
Descriptionarray arraymixed
...
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_chunkSplit an array into chunksDescriptionarray array_chunkarray inputint sizebool preserve_keysarray_chunk splits the array into
several arrays with size values
in them. You may also have an array with less values
at the end. You get the arrays as members of a
multidimensional array indexed with numbers starting
from zero.
By setting the optional preserve_keys
parameter to &true;, you can force PHP to preserve the original
keys from the input array. If you specify &false; new number
indicies will be used in each resulting array with
indices starting from zero. The default is &false;.
array_chunk example
$input_array = array('a', 'b', 'c', 'd', 'e');
$output_array = array_chunk($input_array, 2);
/*
the structure of $output_array will be:
array(
array('a', 'b'),
array('c', 'd'),
array('e')
)
*/
array_count_valuesCounts all the values of an arrayDescriptionarray array_count_valuesarray inputarray_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_diffComputes the difference of arraysDescriptionarray array_diffarray array1array array2array
...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", "red");
$array2 = array ("b" => "green", "yellow", "red");
$result = array_diff ($array1, $array2);
This makes $result have
array ("blue");. Multiple occurences in
$array1 are all treated the same way.
Two elements are considered equal if and only if
(string) $elem1 === (string) $elem2. In words:
when the string representation is the same.
This was broken in PHP 4.0.4!
See also array_intersect.
array_filter
Filters elements of an array using a callback function
Descriptionarray array_filterarray inputmixed
callbackarray_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_flipFlip all the values of an arrayDescriptionarray array_fliparray transarray_flip returns an array in flip
order, i.e. keys from trans become values and
trans's values become keys.
Note that the values of trans need to be valid
keys, i.e. they need to be either integer or
string. A warning will be emitted if a value has the wrong
type, and the key/value pair in question will not be
flipped.
If a value has several occurences, the latest key will be
used as its values, and all others will be lost.
array_flip returns &false;
if it fails.
array_flip example
$trans = array_flip ($trans);
$original = strtr ($str, $trans);
array_flip example : collision
$trans = array ("a" => 1, "b" => 1, "c" => 2);
$trans = array_flip ($trans);
// now $trans is : array(1 => "b", 2 => "c");
array_fillFill an array with valuesDescriptionarray array_fillint start_indexint nummixed valuearray_fill fills an array with
num entries of the value of the
value parameter, keys starting at the
start_index parameter.
array_fill example
$a = array_fill(5, 6, 'banana');
/*
$a now has the following entries:
$a[5] = "banana";
$a[6] = "banana";
$a[7] = "banana";
$a[8] = "banana";
$a[9] = "banana";
$a[10] = "banana";
*/
array_intersectComputes the intersection of arraysDescriptionarray array_intersectarray array1array array2array
...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");
Two elements are considered equal if and only if
(string) $elem1 === (string) $elem2. In words:
when the string representation is the same.
This was broken in PHP 4.0.4!
See also array_diff.
array_keysReturn all the keys of an arrayDescriptionarray array_keysarray inputmixed
search_valuearray_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
Descriptionarray array_mapmixed callbackarray arr1array
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_maparray_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
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_mergeMerge two or more arraysDescriptionarray array_mergearray array1array array2array
...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_recursiveMerge two or more arrays recursivelyDescriptionarray array_merge_recursivearray array1array array2array
...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_multisortSort multiple or multi-dimensional arraysDescriptionbool array_multisortarray ar1mixed
argmixed
...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 orderSORT_DESC - sort in descending order
Sorting type flags:
SORT_REGULAR - compare items normallySORT_NUMERIC - compare items numericallySORT_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
Descriptionarray array_padarray inputint pad_sizemixed pad_valuearray_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_popPop the element off the end of arrayDescriptionmixed array_poparray arrayarray_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
Descriptionint array_pusharray arraymixed varmixed
...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
Descriptionmixed array_randarray inputint
num_reqarray_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 ((float) 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
Descriptionarray array_reversearray arraybool
preserve_keysarray_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 both $result and
$result_keyed be array(array
("green", "red"), 4.0, "php"). But
$result_keyed[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
Descriptionmixed array_reducearray inputmixed callbackint
initialarray_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
Shift an element off the beginning of array
Descriptionmixed array_shiftarray arrayarray_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_sliceExtract a slice of the arrayDescriptionarray array_slicearray arrayint offsetint
lengtharray_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
Descriptionarray array_splicearray inputint offsetint
lengtharray
replacementarray_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")
$input = array ("red", "green", "blue", "yellow");
array_splice ($input, 1, -1);
// $input is now array ("red", "yellow")
$input = array ("red", "green", "blue", "yellow");
array_splice ($input, 1, count($input), "orange");
// $input is now array ("red", "orange")
$input = array ("red", "green", "blue", "yellow");
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.
Descriptionmixed array_sumarray arrarray_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_uniqueRemoves duplicate values from an arrayDescriptionarray array_uniquearray arrayarray_unique takes input
array and returns a new array
without duplicate values.
Note that keys are preserved. array_unique will
keep the first key encountered for every value, and ignore all
following keys.
Two elements are considered equal if and only if
(string) $elem1 === (string) $elem2. In words:
when the string representation is the same.
The first element will be used.
This was broken in PHP 4.0.4!
array_unique example
$input = array ("a" => "green", "red", "b" => "green", "blue", "red");
$result = array_unique ($input);
print_r($result);
// this will output :
//Array
//(
// [a] => green
// [0] => red
// [1] => blue
//)
array_unique and types
$input = array (4,"4","3",4,3,"3");
$result = array_unique ($input);
var_dump($result);
/* output:
array(2) {
[0]=>
int(4)
[1]=>
string(1) "3"
}
*/
array_unshift
Prepend one or more elements to the beginning of array
Descriptionint array_unshiftarray arraymixed varmixed
...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_valuesReturn all the values of an arrayDescriptionarray array_valuesarray inputarray_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
Descriptionint array_walkarray arrstring funcmixed
userdata
Applies the user-defined 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. func
must be a user-defined function, and can't be a native PHP function.
Thus, you can't use array_walk straight with
str2lower, you must build a user-defined function
with it first, and pass this function as argument.
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
Descriptionvoid arsortarray arrayint
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:
a = orange
d = lemon
b = banana
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.
asortSort an array and maintain index associationDescriptionvoid asortarray arrayint
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:
c = apple
b = banana
d = lemon
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
Descriptionarray compactmixed varnamemixed
...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.
countCount elements in a variableDescriptionint countmixed var
Returns the number of elements in var,
which is typically an array (since anything else will have
one element).
If var is not an array, 1 will
be returned (exception: count(&null;) equals
0).
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.
Please see the Arrays
section of the manual for a detailed explanation of how arrays
are implemented and used in PHP.
count example
$a[0] = 1;
$a[1] = 3;
$a[2] = 5;
$result = count ($a);
// $result == 3
$b[0] = 7;
$b[5] = 9;
$b[10] = 11;
$result = count ($b);
// $result == 3;
The sizeof function is an alias for
count.
See also: sizeof,
isset, and
is_array.
currentReturn the current element in an arrayDescriptionmixed currentarray 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 current key and value pair from an array and advance
the array cursor
Descriptionarray eacharray 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 => 01 => 'bob'key => 0value => '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. You have to use
reset if you want to traverse the array
again using each.
See also key, list,
current, reset,
next, and prev.
end
Set the internal pointer of an array to its last element
Descriptionmixed endarray arrayend advances array's
internal pointer to the last element, and returns that element.
See also: current,
each, end,
next, and reset.
extract
Import variables into the symbol table from an array
Descriptionint extractarray var_arrayint
extract_typestring
prefix
This function is used to import variables from an array into the
current symbol table. It takes associative array
var_array and treats keys as variable
names and values as variable values. For each key/value pair it
will create a variable in the current symbol table, subject to
extract_type and
prefix parameters.
Since version 4.0.5 this function returns the number of
variables extracted.
extract checks each key to see whether if
constitutes a valid variable name and also for collisions with
existing variables in the symbol table. The way invalid/numeric
keys and collisions are treated is determined by
extract_type. It can be one of the
following values:
EXTR_OVERWRITE
If there is a collision, overwrite the existing variable.
EXTR_SKIP
If there is a collision, don't overwrite the existing
variable.
EXTR_PREFIX_SAMEIf there is a collision, prefix the variable name with
prefix.
EXTR_PREFIX_ALL
Prefix all variable names with
prefix. Since PHP 4.0.5 this includes
numeric ones as well.
EXTR_PREFIX_INVALID
Only prefix invalid/numeric variable names with
prefix. This flag has been added in
PHP 4.0.5.
If extract_type is not specified, it is
assumed to be EXTR_OVERWRITE.
Note that prefix is only required if
extract_type is EXTR_PREFIX_SAME,
EXTR_PREFIX_ALL, or EXTR_PREFIX_INVALID. If the prefixed result
is not a valid variable name, it is not imported into the symbol
table.
extract returns the number of variables
successfully imported into the symbol table.
A possible use for extract is to import into symbol table
variables contained in an associative array returned by
wddx_deserialize.
extract example
<?php
/* Suppose that $var_array is an array returned from
wddx_deserialize */
$size = "large";
$var_array = array ("color" => "blue",
"size" => "medium",
"shape" => "sphere");
extract ($var_array, EXTR_PREFIX_SAME, "wddx");
print "$color, $size, $shape, $wddx_size\n";
?>
The above example will produce:
blue, large, sphere, medium
The $size wasn't overwritten, because we
specified EXTR_PREFIX_SAME, which resulted in
$wddx_size being created. If EXTR_SKIP was
specified, then $wddx_size wouldn't even have been created.
EXTR_OVERWRITE would have cause $size to have
value "medium", and EXTR_PREFIX_ALL would result in new variables
being named $wddx_color,
$wddx_size, and
$wddx_shape.
You must use an associative array, a numerically indexed array
will not produce results.
See also: compact.
in_arrayReturn &true; if a value exists in an arrayDescriptionbool in_arraymixed needlearray haystackbool
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
<?php
$a = array('1.10', 12.4, 1.13);
if (in_array('12.4', $a, TRUE))
echo "'12.4' found with strict check\n";
if (in_array(1.13, $a, TRUE))
echo "1.13 found with strict check\n";
?>
// 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
Descriptionmixed array_searchmixed needlearray haystackbool 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.
See also in_array.
keyFetch a key from an associative arrayDescriptionmixed keyarray arraykey returns the index element of the
current array position.
See also current and next.
krsortSort an array by key in reverse orderDescriptionint krsortarray arrayint
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:
d = lemon
c = apple
b = banana
a = orange
You may modify the behavior of the sort using the optional
parameter sort_flags, for details
see sort.
See also asort, arsort,
ksortsort,
natsortand rsort.
ksortSort an array by keyDescriptionint ksortarray arrayint
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:
a = orange
b = banana
c = apple
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
Descriptionvoid 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
Descriptionvoid natsortarray 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 information 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
Descriptionvoid natcasesortarray 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
Descriptionmixed nextarray 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.
posGet the current element from an arrayDescriptionmixed posarray array
This is an alias for current.
See also:
end, next,
prev and reset.
prevRewind the internal array pointerDescriptionmixed prevarray 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 elements
Descriptionarray rangemixed lowmixed highrange returns an array of elements from
low to high,
inclusive. If low > high, the sequence will be from high to low.
range examples
foreach(range(0, 9) as $number) {
echo $number;
}
foreach(range('a', 'z') as $letter) {
echo $letter;
}
foreach(range('z', 'a') as $letter) {
echo $letter;
}
Prior to version 4.1.0 the range function
only generated incrementing integer arrays. Support for
character sequences and decrementing arrays was added in 4.1.0.
See shuffle for another example of its use.
reset
Set the internal pointer of an array to its first element
Descriptionmixed resetarray arrayreset 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.
rsortSort an array in reverse orderDescriptionvoid rsortarray arrayint
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:
0 = orange
1 = lemon
2 = banana
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.
shuffleShuffle an arrayDescriptionvoid shufflearray 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 ((float)microtime()*1000000);
shuffle ($numbers);
while (list (, $number) = each ($numbers)) {
echo "$number ";
}
See also arsort, asort,
ksort, rsort,
sort and usort.
sizeofGet the number of elements in variableDescriptionint sizeofmixed var
The sizeof function is an alias for
count.
See also count.
sortSort an arrayDescriptionvoid sortarray arrayint
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."\n";
}
?>
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 these values:
Sorting type flags:
SORT_REGULAR - compare items normallySORT_NUMERIC - compare items numericallySORT_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
Descriptionvoid uasortarray arrayfunction 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
Descriptionvoid uksortarray arrayfunction 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
Descriptionvoid usortarray arraystring 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.