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.
Requirements
These functions are available as part of the standard module, which is
always available.
Installation
There is no installation needed to use these functions, they are part of
the PHP core.
Runtime Configuration
This extension does not define any configuration directives.
Resource types
This extension does not define any resource types.
Predefined constantsCASE_UPPER and CASE_LOWER are
used with the array_change_key_case function. They
respectively are used for chaning a string to upper case or lower case.
See also is_array, explode,
implode, split,
and join.
array
Create an array
Descriptionarrayarraymixed...
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
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
1, 4=>1, 19, 3=>13);
print_r($array);
]]>
will display :
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
'January', 'February', 'March');
print_r($firstquarter);
]]>
will display :
'January'
[2] => 'February'
[3] => 'March'
)
]]>
See also array_pad,
list, and range.
array_change_key_caseReturns an array with all string keys lowercased or uppercasedDescriptionarrayarray_change_key_casearrayinputintcasearray_change_key_case changes the
keys in the input array to
be all lowercase or uppercase. The change depends
on the last optional case
parameter. You can pass two constants there,
CASE_UPPER and
CASE_LOWER. The default is
CASE_LOWER. The function will leave
number indices as is.
array_change_key_case example
1, "SecOnd" => 4);
print_r(array_change_key_case($input_array, CASE_UPPER);
]]>
The printout of the above program will be:
1
[SECOND] => 2
)
]]>
array_chunkSplit an array into chunksDescriptionarrayarray_chunkarrayinputintsizeboolpreserve_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
indices will be used in each resulting array with
indices starting from zero. The default is &false;.
array_chunk example
The printout of the above program will be:
Array
(
[0] => a
[1] => b
)
[1] => Array
(
[0] => c
[1] => d
)
[2] => Array
(
[0] => e
)
)
Array
(
[0] => Array
(
[0] => a
[1] => b
)
[1] => Array
(
[2] => c
[3] => d
)
[2] => Array
(
[4] => e
)
)
]]>
array_count_valuesCounts all the values of an arrayDescriptionarrayarray_count_valuesarrayinputarray_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
The printout of the above program will be:
2
[hello] => 2
[world] => 1
)
]]>
array_diffComputes the difference of arraysDescriptionarrayarray_diffarrayarray1arrayarray2array ...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
"green", "red", "blue", "red");
$array2 = array ("b" => "green", "yellow", "red");
$result = array_diff ($array1, $array2);
]]>
This makes $result have
array ("blue");. Multiple occurrences 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
Descriptionarrayarray_filterarrayinputmixedcallbackarray_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
1, "b"=>2, "c"=>3, "d"=>4, "e"=>5);
$array2 = array (6, 7, 8, 9, 10, 11, 12);
echo "Odd :\n";
print_r(array_filter($array1, "odd"));
echo "Even:\n";
print_r(array_filter($array2, "even"));
]]>
The printout of the program above will be:
1
[c] => 3
[e] => 5
)
Even:
Array
(
[0] => 6
[2] => 8
[4] => 10
[6] => 12
)
]]>
¬e.func-callback;
See also array_map and
array_reduce.
array_flipFlip all the values of an arrayDescriptionarrayarray_fliparraytransarray_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 occurrences, the latest key will be
used as its values, and all others will be lost.
array_flip returns &false;
if it fails.
array_flip examplearray_flip example : collision
1, "b" => 1, "c" => 2);
$trans = array_flip ($trans);
print_r($trans);
]]>
now $trans is :
b
[2] => c
)
]]>
array_fillFill an array with valuesDescriptionarrayarray_fillintstart_indexintnummixedvaluearray_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 now has the following entries using print_r:
banana
[6] => banana
[7] => banana
[8] => banana
[9] => banana
[10] => banana
)
]]>
array_intersectComputes the intersection of arraysDescriptionarrayarray_intersectarrayarray1arrayarray2array ...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
"green", "red", "blue");
$array2 = array ("b" => "green", "yellow", "red");
$result = array_intersect ($array1, $array2);
]]>
This makes $result have
green
[0] => 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_key_existsChecks if the given key or index exists in the arrayDescriptionboolarray_key_existsmixedkeyarraysearcharray_key_exists returns &true; if the
given key is set in the array.
key can be any value possible
for an array index.
array_key_exists example
1, "second" => 4);
if (array_key_exists("first", $search_array)) {
echo "The 'first' element is in the array";
}
]]>
This name of this function is key_exists
in PHP version 4.0.6.
See also isset.
array_keysReturn all the keys of an arrayDescriptionarrayarray_keysarrayinputmixed
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
100, "color" => "red");
print_r(array_keys ($array));
$array = array ("blue", "red", "green", "blue", "blue");
print_r(array_keys ($array, "blue"));
$array = array ("color" => array("blue", "red", "green"), "size" => array("small", "medium", "large"));
print_r(array_keys ($array));
]]>
The printout of the program above will be:
0
[1] => color
)
Array
(
[0] => 0
[1] => 3
[2] => 4
)
Array
(
[0] => color
[1] => 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
See also array_values.
array_map
Applies the callback to the elements of the given arrays
Descriptionarrayarray_mapmixedcallbackarrayarr1arrayarr2...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
This makes $b have:
1
[1] => 8
[2] => 27
[3] => 64
[4] => 125
)
]]>
array_map - using more arrays
$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);
$d = array_map("map_Spanish", $a , $b);
print_r($d);
]]>
This results:
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
)
// printout of $d
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
The printout of the program above will be:
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 and
array_reduce.
array_mergeMerge two or more arraysDescriptionarrayarray_mergearrayarray1arrayarray2array...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
"red", 2, 4);
$array2 = array ("a", "b", "color" => "green", "shape" => "trapezoid", 4);
$result = array_merge ($array1, $array2);
]]>
The $result will be:
green
[0] => 2
[1] => 4
[2] => a
[3] => b
[shape] => trapezoid
[4] => 4
)
]]>
See also array_merge_recursive.
array_merge_recursiveMerge two or more arrays recursivelyDescriptionarrayarray_merge_recursivearrayarray1arrayarray2array...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
array ("favorite" => "red"), 5);
$ar2 = array (10, "color" => array ("favorite" => "green", "blue"));
$result = array_merge_recursive ($ar1, $ar2);
]]>
The $result will be:
Array
(
[favorite] => Array
(
[0] => red
[1] => green
)
[0] => blue
)
[0] => 5
[1] => 10
)
]]>
See also array_merge.
array_multisortSort multiple or multi-dimensional arraysDescriptionboolarray_multisortarrayar1mixedargmixed...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 sorting 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
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
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
Descriptionarrayarray_padarrayinputintpad_sizemixedpad_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 examplearray_popPop the element off the end of arrayDescriptionmixedarray_poparrayarrayarray_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
After this, $stack will have only 3 elements:
orange
[1] => banana
[2] => apple
)
]]>
and rasberry will be assigned to
$fruit.
&return.falseproblem;
See also array_push,
array_shift, and
array_unshift.
array_push
Push one or more elements onto the end of array
Descriptionintarray_pusharrayarraymixedvarmixed...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:
repeated for each var.
Returns the new number of elements in the array.
array_push example
This example would result in $stack having
the following elements:
orange
[1] => banana
[2] => apple
[3] => raspberry
)
]]>
See also array_pop,
array_shift, and
array_unshift.
array_rand
Pick one or more random entries out of an array
Descriptionmixedarray_randarrayinputintnum_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 examplearray_reverse
Return an array with elements in reverse order
Descriptionarrayarray_reversearrayarrayboolpreserve_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
This makes both $result and
$result_keyed have the same elements, but
note the difference between the keys. The printout of
$result and
$result_keyed will be:
Array
(
[0] => green
[1] => red
)
[1] => 4
[2] => php
)
Array
(
[2] => Array
(
[0] => green
[1] => red
)
[1] => 4
[0] => 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
Descriptionmixedarray_reducearrayinputmixedcallbackintinitialarray_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 initial is
available, it will be used at the beginning of the process, or as
a final result in case the array is empty.
array_reduce example
This will result in $b containing
15, $c containing
1200 (= 1*2*3*4*5*10), and
$d containing 1.
See also array_filter and
array_map.
array_shift
Shift an element off the beginning of array
Descriptionmixedarray_shiftarrayarrayarray_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
This would result in $stack having 3 elements left:
banana
[1] => apple
[2] => raspberry
)
]]>
and orange will be assigned to
$fruit.
See also array_unshift,
array_push, and
array_pop.
array_sliceExtract a slice of the arrayDescriptionarrayarray_slicearrayarrayintoffsetint
length
array_slice returns the sequence of elements
from the array array as 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.
Note that array_slice will ignore array
keys, and will calculate offsets and lengths based on the
actual positions of elements within the array.
array_slice examples
See also array_splice.
array_splice
Remove a portion of the array and replace it with something
else
Descriptionarrayarray_splicearrayinputintoffsetintlengtharray
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. It returns an array containing the extracted elements.
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:
Returns the array consisting of removed elements.
array_splice examples
See also array_slice.
array_sum
Calculate the sum of values in an array.
Descriptionmixedarray_sumarrayarrayarray_sum returns the sum of values
in an array as an integer or float.
array_sum examples
1.2,"b"=>2.3,"c"=>3.4);
echo "sum(b) = ".array_sum($b)."\n";
]]>
The printout of the program above will be:
PHP versions prior to 4.0.6 modified the passed array
itself and converted strings to numbers (which most
of the time converted them to zero, depending on
their value).
array_uniqueRemoves duplicate values from an arrayDescriptionarrayarray_uniquearrayarrayarray_unique takes input
array and returns a new array
without duplicate values.
Note that keys are preserved. array_unique sorts
the values treated as string at first, then will keep the first key
encountered for every value, and ignore all following keys. It does not
mean that the key of the first related value from the unsorted
array will be kept.
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
"green", "red", "b" => "green", "blue", "red");
$result = array_unique ($input);
print_r($result);
]]>
This will output:
green
[1] => blue
[2] => red
)
]]>
array_unique and types
The printout of the program above will be (PHP 4.0.6):
int(4)
[4]=>
int(3)
}
]]>
array_unshift
Prepend one or more elements to the beginning of array
Descriptionintarray_unshiftarrayarraymixedvarmixed
...
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
This would result in $queue having the
following elements:
apple
[1] => raspberry
[2] => orange
[3] => banana
)
]]>
See also array_shift,
array_push, and
array_pop.
array_valuesReturn all the values of an arrayDescriptionarrayarray_valuesarrayinputarray_values returns all the values from the
input array.
array_values example
"XL", "color" => "gold");
print_r(array_values ($array));
]]>
This will output:
XL
[1] => 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
See also array_keys.
array_walk
Apply a user function to every member of an array
Descriptionintarray_walkarrayarraystringfuncmixeduserdata
Applies the user-defined function named by func
to each element of array.
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.
¬e.func-callback;
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.
Modifying the array from inside func
may cause unpredictable behavior.
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
"lemon", "a"=>"orange", "b"=>"banana", "c"=>"apple");
function test_alter (&$item1, $key, $prefix) {
$item1 = "$prefix: $item1";
}
function test_print ($item2, $key) {
echo "$key. $item2 \n";
}
echo "Before ...:\n";
array_walk ($fruits, 'test_print');
reset ($fruits);
array_walk ($fruits, 'test_alter', 'fruit');
echo "... and after:\n";
reset ($fruits);
array_walk ($fruits, 'test_print');
]]>
The printout of the program above will be:
See also each and list.
arsort
Sort an array in reverse order and maintain index association
Descriptionvoidarsortarrayarrayintsort_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
"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:
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 associationDescriptionvoidasortarrayarrayintsort_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
"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:
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
Descriptionarraycompactmixedvarnamemixed...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
After this, $result will be:
SIGGRAPH
[city] => San Francisco
[state] => CA
)
]]>
See also extract.
countCount elements in a variableDescriptionintcountmixedvar
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
The sizeof function is an
alias for count.
See also is_array,
isset, and
strlen.
currentReturn the current element in an arrayDescriptionmixedcurrentarrayarray
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
Descriptionarrayeacharrayarray
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$bar now contains the following key/value
pairs:
0 => 01 => 'bob'key => 0value => 'bob'
"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
";
reset ($HTTP_POST_VARS);
while (list ($key, $val) = each ($HTTP_POST_VARS)) {
echo "$key => $val ";
}
]]>
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
Descriptionmixedendarrayarrayend advances array's
internal pointer to the last element, and returns that element.
See also current,
each,
next, and reset.
extract
Import variables into the current symbol table from an array
Descriptionintextractarrayvar_arrayintextract_typestringprefix
This function is used to import variables from an array into the
current symbol table. It takes an 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.
EXTR_IF_EXISTS and EXTR_PREFIX_IF_EXISTS was introduced in version 4.2.0.
extract checks each key to see whether it
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 was added in
PHP 4.0.5.
EXTR_IF_EXISTS
Only overwrite the variable if it already exists in the
current symbol table, otherwise do nothing. This is useful
for defining a list of valid variables and then extracting
only those variables you have defined out of $_REQUEST, for
example. This flag was added in PHP 4.2.0.
EXTR_PREFIX_IF_EXISTS
Only create prefixed variable names if the non-prefixed version
of the same variable exists in the current symbol table. This
flag was added in PHP 4.2.0.
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, EXTR_PREFIX_INVALID or EXTR_PREFIX_IF_EXISTS. 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 the symbol table
variables contained in an associative array returned by
wddx_deserialize.
extract example
"blue",
"size" => "medium",
"shape" => "sphere");
extract ($var_array, EXTR_PREFIX_SAME, "wddx");
print "$color, $size, $shape, $wddx_size\n";
?>
]]>
The above example will produce:
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 caused $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 unless you use EXTR_PREFIX_ALL or
EXTR_PREFIX_INVALID.
See also compact.
in_arrayReturn &true; if a value exists in an arrayDescriptionboolin_arraymixedneedlearrayhaystackboolstrict
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 function
will also check the types of
the needle in the haystack.
If needle is a string, the comparison is done in
a case-sensitive manner.
In PHP versions before 4.2.0 needle was not
allowed to be an array.
in_array example
The second condition fails because in_array
is case-sensitive, so the program above will display:
in_array with strict example
]]>
This will display:
in_array with an array as needle
// This will output:
'ph' is found
'o' is found
]]>
See also array_search.
array_search
Searches the array for a given value and returns the
corresponding key if successful
Descriptionmixedarray_searchmixedneedlearrayhaystackboolstrict
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.
&return.falseproblem;
See also in_array.
keyFetch a key from an associative arrayDescriptionmixedkeyarrayarraykey returns the index element of the
current array position.
See also current and next.
krsortSort an array by key in reverse orderDescriptionintkrsortarrayarrayintsort_flags
Sorts an array by key in reverse order, maintaining key to data
correlations. This is useful mainly for associative arrays.
krsort example
"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:
You may modify the behavior of the sort using the optional
parameter sort_flags, for details
see sort.
See also asort, arsort,
ksort, sort,
natsort, and rsort.
ksortSort an array by keyDescriptionintksortarrayarrayintsort_flags
Sorts an array by key, maintaining key to data correlations. This
is useful mainly for associative arrays.
ksort example
"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:
You may modify the behavior of the sort using the optional
parameter sort_flags, for details
see sort.
See also asort, arsort,
krsort, uksort,
sort, natsort, and
rsort.
The second parameter was added in PHP 4.
list
Assign variables as if they were an array
Descriptionvoidlistmixed...
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
\n".
" \n");
}
?>
]]>
See also each and array.
natsort
Sort an array using a "natural order" algorithm
Descriptionvoidnatsortarrayarray
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
The code above will generate the following output:
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
Descriptionvoidnatcasesortarrayarray
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 information 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
Descriptionmixednextarrayarray
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 arrayDescriptionmixedposarrayarray
This is an alias
for current.
See also
end, next,
prev, and reset.
prevRewind the internal array pointerDescriptionmixedprevarrayarray
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
Descriptionarrayrangemixedlowmixedhighrange returns an array of elements from
low to high,
inclusive. If low > high, the sequence will be from high to low.
range examples
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.
Simulating decrementing ranges and character sequences
See shuffle for another example of its use.
reset
Set the internal pointer of an array to its first element
Descriptionmixedresetarrayarrayreset 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 orderDescriptionvoidrsortarrayarrayintsort_flags
This function sorts an array in reverse order (highest to lowest).
rsort example
This example would display:
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 arrayDescriptionvoidshufflearrayarray
This function shuffles (randomizes the order of the elements in)
an array. You must use srand to seed this
function.
shuffle example
See also arsort, asort,
ksort, rsort,
sort, and usort.
sizeofGet the number of elements in variableDescriptionintsizeofmixedvar
The sizeof function is an
alias for count.
See also count.
sortSort an arrayDescriptionvoidsortarrayarrayintsort_flags
This function sorts an array. Elements will be arranged from
lowest to highest when this function has completed.
sort example
]]>
This example would display:
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
Descriptionvoiduasortarrayarrayfunctioncmp_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.
¬e.func-callback;
See also usort, uksort,
sort, asort,
arsort, ksort,
and rsort.
uksort
Sort an array by keys using a user-defined comparison function
Descriptionvoiduksortarrayarrayfunctioncmp_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
$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:
¬e.func-callback;
See also usort, uasort,
sort, asort,
arsort, ksort,
natsort, and rsort.
usort
Sort an array by values using a user-defined comparison function
Descriptionvoidusortarrayarraystringcmp_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
$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:
Obviously in this trivial case the rsort
function would be more appropriate.
usort example using multi-dimensional array
When sorting a multi-dimensional array, $a and $b contain
references to the first index of the array.
This example would display:
¬e.func-callback;
usort example using a member function of an object
name = $name;
}
/* This is the static comparing function: */
function cmp_obj($a, $b)
{
$al = strtolower($a->name);
$bl = strtolower($b->name);
if ($al == $bl) return 0;
return ($al > $bl) ? +1 : -1;
}
}
$a[] = new TestObj("c");
$a[] = new TestObj("b");
$a[] = new TestObj("d");
uasort($a, array ("TestObj", "cmp_obj"));
foreach ($a as $item) {
print $item->name."\n";
}
]]>
This example would display:
b
c
d
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.