Array functions
Arrays
array
Create an array
Description
array array
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.
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")
);
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)
This function was added in PHP 4.0.
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);
This function was added in PHP 4.0.
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(1, 100, 2, 100);
array_keys ($array, 100); // returns array (0, 2)
See also array_values.
This function was added in PHP 4.0.
array_merge
Merge two or more arrays
Description
array array_merge
array array1
array array2
...
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 had the same string keys, then the later
value for that key will overwrite previous one. If, however, the
arrays have the same numeric key, this does not happen since the
values are appended.
array_merge example
$array1 = array ("color" => "red", 2, 4);
$array2 = array ("a", "b", "color" => "green", "shape" => "trapezoid");
array_merge ($array1, $array2);
Resulting array will be array("color" => "green", 2, 4, "a",
"b", "shape" => "trapezoid").
This function was added in PHP 4.0.
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.
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.
This function was added in PHP 4.0.
array_push
Push one or more elements onto the end of array
Description
int array_push
array array
mixed var
...
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.
This function was added in PHP 4.0.
array_reverse
Return an array with elements in reverse order
Description
array array_reverse
array array
array_reverse takes input
array and returns a new array with the
order of the elements reversed.
array_reverse example
$input = array ("php", 4.0, array ("green", "red"));
$result = array_reverse ($input);
This makes $result have array (array ("green", "red"), 4.0, "php").
This function was added in PHP 4.0 Beta 3.
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.
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.
This function was added in PHP 4.0.
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.
This function was added in PHP 4.0.
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.
This function was added in PHP 4.0.
array_unshift
Push one or more elements
onto the beginning of array
Description
int array_unshift
array array
mixed var
...
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.
This function was added in PHP 4.0.
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 in PHP 4.0.
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
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);
for (reset ($fruits); $key = key ($fruits); next ($fruits)) {
echo "fruits[$key] = ".$fruits[$key]."\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.
See also: asort, rsort,
ksort, and sort.
asort
Sort an array and maintain index association
Description
void asort
array array
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);
for (reset ($fruits); $key = key ($fruits); next ($fruits)) {
echo "fruits[$key] = ".$fruits[$key]."\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.
See also arsort, rsort,
ksort, and sort.
compact
Create array containing variables and their values
Description
array compact
string varname | array
varnames
...
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.
compact example
$city = "San Francisco";
$state = "CA";
$event = "SIGGRAPH";
$location_vars = array ("city", "state");
$result = compact ("event", $location_vars);
After this, $result will be array ("event" => "SIGGRAPH",
"city" => "San Francisco", "state" => "CA").
See also extract.
This function was added in PHP 4.0.
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.
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
end
array array
end advances array's
internal pointer to the last 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
Searches haystack for
needle and returns true if it is found in
the array, false otherwise.
in_array example
$os = array ("Mac", "NT", "Irix", "Linux");
if (in_array ("Irix", $os))
print "Got Irix";
This function was added in PHP 4.0.
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, next
krsort
Sort an array by key in reverse order
Description
int krsort
array array
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);
for (reset ($fruits); $key = key ($fruits); next ($fruits)) {
echo "fruits[$key] = ".$fruits[$key]."\n";
}
This example would display:
fruits[d] = lemon
fruits[c] = apple
fruits[b] = banana
fruits[a] = orange
See also asort, arsort,
ksort sort, and
rsort.
ksort
Sort an array by key
Description
int ksort
array array
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);
for (reset ($fruits); $key = key ($fruits); next ($fruits)) {
echo "fruits[$key] = ".$fruits[$key]."\n";
}
This example would display:
fruits[a] = orange
fruits[b] = banana
fruits[c] = apple
fruits[d] = lemon
See also asort, arsort,
sort, and rsort.
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($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, array.
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 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.
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,
prev, and reset.
rsort
Sort an array in reverse order
Description
void rsort
array array
This function sorts an array in reverse order (highest to lowest).
rsort example
$fruits = array ("lemon", "orange", "banana", "apple");
rsort ($fruits);
for (reset ($fruits); list ($key, $value) = each ($fruits); ) {
echo "fruits[$key] = ", $value, "\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.
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.
shuffle example
$numbers = range (1,20);
srand (time());
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
This function sorts an array. Elements will be arranged from
lowest to highest when this function has completed.
sort example
$fruits = array ("lemon", "orange", "banana", "apple");
sort ($fruits);
for (reset ($fruits); $key = key ($fruits); next ($fruits)) {
echo "fruits[$key] = ".$fruits[$key]."\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.
See also: arsort,
asort, ksort,
rsort, and usort.
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.
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 mycompare ($a, $b) {
if ($a == $b) return 0;
return ($a > $b) ? -1 : 1;
}
$a = array (4 => "four", 3 => "three", 20 => "twenty", 10 => "ten");
uksort ($a, mycompare);
while (list ($key, $value) = each ($a)) {
echo "$key: $value\n";
}
This example would display:
20: twenty
10: ten
4: four
3: three
See also: arsort,
asort, uasort,
ksort, rsort, and
sort.
usort
Sort an array by values using a user-defined comparison function
Description
void usort
array array
function 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.
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: arsort,
asort, ksort,
rsort and sort.