This document is compiled from the PHP learning manual. During the use, I found that array functions are widely used. I will sort them out today for easy reference and reference in the future. use.
Syntax: array array([mixed ...]);
Description:
Returns an array of parameters. The parameters can be given index values using the "=>" operator. This function is not a regular function and is mainly used to represent arrays.
$arr=array(0=>123,2=>’tere’);
array_count_values --- Calculate all values of the array
Syntax: array array_count_values(array input);
Description:
This function returns a calculated array result. The index value of the returned array is the value of the parameter input, and the value of the array is the number of times the parameter input appears.
Example :
$array = array(1, "hello", 1, "world", "hello");
array_count_values($array); //returns array(1 => 2, "hello" => 2, "world" => 1)
?>
Syntax: array array_diff (array array1, array array2 [, array ...])
Description:
Array_diff() returns all values of array1 that do not appear in other arguments. This function returns an array type, and the index value of the returned array will be retained.
Example :
$array1 = array ("a" => "green", "red", "blue");
$array2 = array ("b" => "green", "yellow", "red");
$result = array_diff ($array1, $array2);
?>
This will make $result have array("blue")
Syntax: array array_flip(array trans);
Description: This function returns the array in flip order.
Example :
$trans = array_flip($trans);
$original = strtr($str, $trans);
?>
Syntax: array array_intersect (array array1, array array2 [, array ...])
Description:
Array_intersect() returns all the values of array1 that appear in all arguments. This function will return an array type, and the index value of the returned array will be retained.
Example :
$array1 = array ("a" => "green", "red", "blue");
$array2 = array ("b" => "green", "yellow", "red");
$result = array_intersect ($array1, $array2);
?>
This will make $result have array( "a" => "green" , "red" )
Syntax: array array_keys(array input [ , mixed search_value] );
Description:
This function returns the index value of the number and string from the parameter input. The parameter search_value is optional. If specified, only the index value of the specified value will be returned. Otherwise, all index values will be returned from the input.
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)
?>
Syntax: array array_merge(array array1, array array2 [ , array ...] );
Description:
This function combines two or more arrays together so that their values are appended to the previous one. If the input array has the same string index value, the subsequent value will overwrite the previous value. However, the array has the same numeric index, but the subsequent value will not overwrite the original value, but will be attached.
Example :
$array1 = array("color" => "red", 2, 4);
$array2 = array("a", "b", "color" => "green", "shape" => "trapezoid");
array_merge($array1, $array2);
?>
The generated array will be array("color" => "green", 2, 4, "a", "b", "shape" => "trapezoid")
Syntax: array array_merge_recursive (array array1, array array2 [, array ...])
Description:
Array_merge_recursive() merges two or more arrays together so that their values are appended to the previous one.
If the input arrays have the same string index value, then these values will be merged into the array, and in a recursive manner, so if the value itself is an array, this function will merge it in another in an array. Regardless, the array has the same numeric index, but subsequent values will not overwrite the previous value, but will be appended to it.
Example :
$ar1 = array ("color" => array ("favorite" => "red"), 5);
$ar2 = array (10, "color" => array ("favorite" => "green", "blue"));
$result = array_merge_recursive ($ar1, $ar2);
?>
The resulting array will be
array( "color" => array ( "favorite" => array( "red" , "green" ), "blue" ),5 ,10)
Syntax: bool array_multisort (array ar1 [,mixed arg [,mixed ...[,array...]]])
Description:
Array_multisort() can be used to sort several arrays or multi-dimensional arrays at once.
The input array is regarded as a field of the table and is sorted according to the rows. This is similar to the function of the SQL ORDER BY clause. The first array is the primary sorted array. The columns (values) in this array are sorted in the same order as the next input array.
The argument structure of this function is a unique bit, but it is flexible. The first argument must be an array, and subsequent arguments can be an array or one of the sort flags of the next list.
Sort order flag:
SORT_ASC - Sort in ascending order
SORT_DESC - Sort in descending order
Sort type flag:
SORT_REGULAR - normal comparison item
SORT_NUMERIC - Compare items numerically
SORT_STRING - Compare items as strings
You cannot use two flags of the same type specified after each array. The sorting flag is specified after the array argument. It only affects this array. Others will be reset to the default SORT_ASC and SORT_REGULAR. after the array argument.
Returns true if successful and false if failed.
Example :
$ar1 = array ("10", 100, 100, "a");
$ar2 = array (1,3,"2",1);
array_multisort ($ar1,$ar2);
?>
After sorting this example, the first array will be 10, "a", 100, 100, and the second array will be 1, 1, 2, "3".
Example :
$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);
?>
After sorting in this example, the first array will be 10 , 100 , 100 , "a" (it is treated as a string and sorted ascendingly), and the second array will be 1 , 3 , "2" , 1 (it is treated as a numeric value and sorted descendingly).
Syntax: array array_pad(array input, int pad_size, mixed pad_value);
Description:
This function fills the array array into an array with a size of pad_size and a value of pad_value, and returns the filled array. If the parameter pad_size is a positive number, it will be filled to the right of the array. If it is a negative number, then Pad to the left of the array. If the absolute value of the parameter pad_size is less than or equal to the length of the array input, there will be no padding.
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
?>
Syntax: mixed array_pop(array array);
Description: This function returns the last element of the array, shortening the array by one element.
Example :
$stack = array("orange", "apple", "raspberry");
$fruit = array_pop($stack);
?>
After this, $stack has only two elements "orange" and "apple", and $fruit is "raspberry".
Syntax: int array_push(array array, mixed var [ , mixed ...] );
Description:
This function treats the parameter array as a stack, and the extension variable is above the end of the parameter array. The length of the parameter array increases according to the number of variables.
Has the same effect:
$array[ ] = $var;
?>
Repeat each var.
Returns the new number of elements in the array.
Example :
$stack = array(1, 2);
array_push($stack, " ", 3);
?>
This example will make $stack have four elements: 1, 2, " " and 3
Syntax: mixed array_rand (array input [, int num_req])
Description:
Array_rand() is very useful when you want to randomly select one or more values from an array. The argument num_reg is optional. It indicates how many values you want to select. If not specified, its preset Let the value be 1.
If you only pick a single value, array_rand() returns the index of the random value. Otherwise, it returns the index of the random value placed in the array and returns this array. This way you can not only pick random index values but also output the array values.
Don’t forget to call srand() to set the random seed.
Example :
srand ((double) microtime() * 10000000);
$input = array ("Neo", "Morpheus", "Trinity", "Cypher", "Tank");
$rand_keys = array_rand ($input, 2);
print $input[$rand_keys[0]]."n";
print $input[$rand_keys[1]]."n";
?>
Syntax: array array_reverse(array array);
Description: This function reverses the order of the elements of the parameter array and returns the new array.
Example :
$input = array("php", 4.0, array("green", "red"));
$result = array_reverse($input);
?>
This example makes $result become array(array("green", "red"), 4.0, "php").
Syntax: mixed array_shift(array array);
Description:
This function moves the first element of the array and passes it back, shortening the array by one element and moving it all down.
Example :
$args = array("-v", "-f");
$opt = array_shift($args);
?>
This example will make $arge have an element "-f", and $opt have "-v".
Syntax: array array_slice(array array, int offset, int [length] );
Description:
This function returns a part of the element from the array. If offset is a positive number, the retrieved part will start from the offset in the array; if offset is a negative number, it will start from the end of the array. If length is given and is a positive number, length elements will be retrieved. If length is a negative number, it will stop at the length element at the end of the array. If this parameter is omitted, the returned part will be from offset to the array. end.
Example :
$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"
?>
Syntax: array array_splice(array input, int offset, int [length], array [replacement]);
Description:
This function removes the array input from offset to length. If the parameter replacement is provided, it will be replaced by the element of replacement.
If offset is a positive number, the removal starts from the offset position at the beginning of the array array. If offset is a negative number, it starts from the end of the array array.
If the length parameter is omitted, the removed part is from offset to the end of the array. If length is specified and it is a positive number, length elements will be removed. If length is specified and it is a negative number, the removed part will stop. The length element at the end of the array.
If the replacement parameter is specified, the removed elements will be replaced with elements of this array. If offset and length are not removed, the elements in replacement will be inserted at the location specified by offset.
The following meanings are equivalent:
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)
Example :
$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")
?>
语法 : array array_unique (array array)
说明 :
Array_unique( )取输入的数组array且传回没有相同的值的数组。索引会被保留(preserved)。
Example :
$input = array ("a" => "green", "red", "b" => "green", "blue", "red");
$result = array_unique ($input);
?>
这将使$result有着array ( "a" => "green" , "red" , "blue");
语法 : int array_unshift(array array, mixed var, [...] );
说明 :
此函数增加元素到数组array的前面,此函数传回数组array中新的元素数目。
Example :
$queue = array("p1", "p3");
array_unshift($queue, "p4", "p5", "p6");
?>
此范例将会使$queue有五个元素:"p4","p5","p6","p1"和"p3"。
语法 : array array_values(array input);
说明 :
此函数从数组array传回所有的值。
Example :
$array = array("size" => "XL", "color" => "gold");
array_values($array); // returns array("XL", "gold")
?>
语法 : int array_walk(array arr , string func);
说明 :
使数组arr的每个元素和函数名称func相对应,元素传到函数func的第一个参数,如果函数func超过一个以上的参数,则会有警告讯息,要抑制警告讯息可在此函数前加上’@’,即@array_walk,或是使用error_reporting。
注意 : 此函数确实会将数组arr的每个元素依序代入,因此任何元素的改变都将影响数组本身。
注意 : PHP4.0.新增传送索引(key)和使用者资料(userdata)到函数func。在PHP4中array_walk( )预设不重设(reset)数组,因此必须要呼叫reset( )
Example :
$fruits = array("d" => "lemon" , "a" => "orange" ,"b" => "banana" , "c" => "apple");
function test_alter($item1) {
$item1 = 'bogus';
}
function test_print($item2) {
echo "$item2
n";
}
array_walk($fruits , 'test_print');
reset ($fruits);
array_walk($fruits , 'test_alter');
reset ($fruits);
array_walk($fruits , 'test_print');
?>
语法 : void arsort(array array);
说明 :
此函数颠倒数组元素的顺序(z-a),且维持数组元素与其索引值对应的关系,这个函数主要是用于需要将数组元素的顺序作颠倒的排列。
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";
}
?>
此范例的结果为 :
fruits[a] = orange
fruits[d] = lemon
fruits[b] = banana
fruits[c] = apple
It can be seen that the order of the array fruits has been reversed, and the relationship between the index value and the elements remains the same.
Syntax: void asort(array array);
Description:
This function rearranges the elements of the array from a-z, and maintains the corresponding relationship between the original index value and the element. This function is mainly used to rearrange the elements of the array.
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";
}
?>
The result of this example is:
fruits[c] = apple
fruits[b] = banana
fruits[d] = lemon
fruits[a] = orange
It can be seen that the array fruits has been rearranged, and the relationship between the index values and elements remains unchanged.
Syntax: array compact(string varname | array varnames, [...] );
Description:
This function takes the number of variable parameters. Each variable can be a string containing a variable name or an array name of a variable. The array can contain the array names of other variables.
This function looks for the variable name in the symbol table and adds it to the output array, so that the name of the variable becomes the index value and the content of the variable becomes the value of this index value. This function and extract( )In contrast, this function returns the output array.
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")
Syntax: int count(mixed var);
Description:
Returns the number of elements in the parameter var. The most typical example is to calculate the number of elements in an array.
If the variable is not set, 0 is returned, if the variable is not an array, 1 is returned.
Warning:
When the variable is not set, count() may return 0, but when the beginning of the variable is an empty array, it will also return 0. You can use isset() to test.
Syntax: mixed current(array array);
Description:
Each array has an internal pointer pointing to its current element. The pointer will point to the first element inserted into the array until the program executes a function with a moving pointer. This function will return the value pointed to by the internal pointer. Array element, and will not move the position of the pointer. If the internal pointer points outside the array element, false will be returned. If the array contains empty elements (0 or ""), false will be returned.
Syntax: array each(array array);
Description:
Return the current key/value pair from the array and move the array cursor forward. The array returned has four elements, namely 0, 1, key and value. The elements 0 and key are the names of the array index values, and 1 and value are the data of the elements. If the array's internal pointer points to the end of the array, this function returns false.
Example :
$foo = array("bob" , "fred" , "jussi" , "jouni");
$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 usually used together with list, for example: $HTTP_POST_VARS
Example :
echo "Values submitted via POST method:
";
while(list($key , $val) = each($HTTP_POST_VARS)) {
echo "$key => $val
";
}
?>
Aftereach() is executed, the cursor of the array will be on the left side of the next element of the array. If the end of the array is reached, the cursor will be on the last element.
Syntax: end(array array);
Description:
This function sets the internal index of the array to the last element
Syntax: void extract(array var_array, int [extract_type], string [prefix]);
Description:
This function inputs variables from the array into the current symbol table. It takes the array var_array and treats the index value as the variable name and the value as the variable value. It creates a variable for each key/value pair in the current symbol table. , based on extract_type and prefix.
extract() checks the existing variables. The parameter extract determines how to handle collisions. It can be one of the following values:
EXTR_OVERWRITE
If a collision occurs, existing variables will be overwritten
EXTR_SKIP
If a collision occurs, existing variables will not be overwritten
EXTR_PREFIX_SAME
If a collision occurs, the parameter prefix will be added in front of the prefix to become a new variable
EXTR_PREFIX_ALL
Add the parameter prefix to the capital words of all variables
If the parameter extract_type is not specified, EXTR_OVERWRITE is used.
Note: The parameter prefix is only required when extract_type is EXTR_PREFIX_SAME or EXTR_PREFIX_ALL.
Example :
/* 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_sizen";
?>
The above example will produce:
blue, large, sphere, medium
$size is not overwritten because we specified EXTR_PREFIX_SAME and the result in $wddx_size has been created. If EXTR_SKIP is used, $wddx_size will not be created. If EXTR_OVERWRITE is used, the value of $size is medium. If Using EXTR_PREFIX_ALL there will be new variables named $wddx_color, $wddx_size and $wddx_shape.
Syntax: bool in_array(mixed needle, array haystack);
Description:
This function searches the array haystack to see if the parameter needle exists in the array. If it is found in the array, it returns true, otherwise it returns false.
Example :
$os = array("Mac", "NT", "Irix", "Linux");
if (in_array("Irix", $os))
print "Got Irix";
?>
Syntax: mixed key(array array);
Description:
This function returns the index pointed to by the current array pointer.
Syntax: int krsort(array array);
Description:
Rearrange the array in the reverse order of the index values (z-a), while the original relationship between the index values and the array values remains.
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";
}
?>
The result of this example is:
fruits[d] = lemon
fruits[c] = apple
fruits[b] = banana
fruits[a] = orange
Syntax: int ksort (array array [, int sort_flags] ) );
Description:
This function rearranges the array from a-z according to the index value
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";
}
The result of this example is:
fruits[a] = orange
fruits[b] = banana
fruits[c] = apple
fruits[d] = lemon
Syntax: void list(...);
Description:
Similar to array(), this function is not a regular function. This function is used to allocate a list of variables in an operation.
Example :
Salary | |
---|---|
$name | n".$salary | n"."
Syntax: mixed next(array array);
Description:
Returns the next element pointed to by the internal index of the array. If there is no next element, false will be returned.
This function is similar to current(), but one difference is that this function will first move the internal index of the array before returning the element, which means that this function will return the next element of the array and move the interior of the array. Index, if the internal index of the array points outside the elements of the array, false will be returned.
Warning: If the array contains empty elements, this function will return false. To handle empty elements in the array, use the each() function.
Syntax: mixed pos(array array);
Description:
This function is an alias of current().
Syntax: mixed prev(array array);
Description:
Returns the array element pointed to by the internal pointer of the previous array, or returns false if there is no previous element.
Warning: If the array contains empty elements, this function will return false. To handle empty elements in the array, use the each() function.
This function is similar to next(). prev() moves the internal pointer of the array backward instead of the forward movement of next().
Syntax: array range(int low, int high);
Description:
Returns an array of integers from low to high
Syntax: mixed reset(array array);
Description:
reset() resets the internal index of the array to its first element.
reset() returns the value of the first element of the array.
Syntax: void rsort(array array);
Description:
This function rearranges the values of the array by z-a.
Example :
$fruits = array("lemon","orange","banana","apple");
rsort($fruits);
reset($fruits);
for ($i=0; $i echo
"fruits[$i] = ".$fruits[$i]." } ?> The result of this example will be: fruits[0] =
orange fruits[1] =
lemon fruits[2] =
banana fruits[3] = apple Fruits are arranged in the order of z-a Syntax: void
shuffle(array array); Description: This function sorts the elements of the array in any order. Example :
$numbers = range(1,20);
srand(time());
shuffle($numbers);
while (list(,$number) = each($numbers)) {
echo "$number "; } ?> Syntax: int sizeof(array
array); Description: Returns the number of elements in the array. Syntax: void sort(array
array [, int sort_flags] ); Description: This function will arrange the elements of the array from a-z. Example :
$fruits =
array("lemon","orange","banana","apple");
sort($fruits); for(reset($fruits);
$key = key($fruits); next($fruits)) { echo
"fruits[$key] = ".$fruits[$key]."n"; } ?> The result of this example will be: fruits[0] =
apple fruits[1] =
banana fruits[2] =
lemon fruits[3] = orange Fruits are arranged in the order from a-z The optional second parameter sort_flags can use the following values to change the sorting: Sort type flag: SORT_REGULAR - normal comparison item SORT_NUMERIC - Compare items numerically SORT_STRING - Compare items as strings Syntax: void uasort(array
array, function cmp_function); Description: This function can reorder the array according to the user-defined function, while the index value of the array and the elements still maintain the original relationship. Reference usort()
There are usage examples for uksort() Syntax: void uksort(array
array, function cmp_function); Description: This function will reorder the index values of the array according to the user-defined function. 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: $valuen"; } ?> The result of this example will be: 20: twenty 10: ten
4: four 3: three Syntax: void usort(array
array, function cmp_function); Description: This function will reorder the values of the array according to the user-defined function. 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: $valuen"; } ?> The result of this example will be: 0: 6 1: 5 2: 3 3:
2 4: 1
";