A simple usage of the array_push() function. This is a commonly used function for array operations. Friends in need can refer to it
(PHP 4, PHP 5)
array_push — Push one or more elements to the end of an array (push)
Report a bug Description
int array_push ( array &$array , mixed $var [, mixed $... ] )
array_push() treats the array as a stack and pushes the passed variables to the end of the array. The length of array will increase according to the number of variables pushed onto the stack. The same effect as the following:
The code is as follows
代码如下 |
复制代码 |
$array[] = $var;
?>
|
|
Copy code
|
$array[] = $var;
?>
代码如下 |
复制代码 |
$a=array("Dog","Cat");
array_push($a,"Horse","Bird");
print_r($a);
?> |
Repeat for each var.
Returns the new total number of cells in the array.
代码如下 |
复制代码 |
$a=array("a"=>"Dog","b"=>"Cat");
array_push($a,"Horse","Bird");
print_r($a);
?> |
Example 1
The code is as follows
|
Copy code
|
$a=array("Dog","Cat");
array_push($a,"Horse","Bird");
print_r($a);
?>
Output:
Array ( [0] => Dog [1] => Cat [2] => Horse [3] => Bird ) Example 2
Array with string keys:
代码如下 |
复制代码 |
function array_pshift(&$array) {
$keys = array_keys($array);
$key = array_shift($keys);
$element = $array[$key];
unset($array[$key]);
return $element;
}
?>
|
The code is as follows |
Copy code |
|
$a=array("a"=>"Dog","b"=>"Cat");
array_push($a,"Horse","Bird");
print_r($a);
?>
Output:
Array ( [a] => Dog [b] => Cat [0] => Horse [1] => Bird )
Note: If you use array_push() to add a unit to the array, it is better to use $array[] = because there is no additional burden of calling the function.
Note: array_push() will issue a warning if the first argument is not an array. This is different from the behavior of $var[], which creates a new array.
See array_pop(), array_shift() and array_unshift().
If you want to preserve the keys in the array, use the following:
The code is as follows
|
Copy code
|
function array_pshift(&$array) { <🎜>
$keys = array_keys($array); <🎜>
$key = array_shift($keys); <🎜>
$element = $array[$key]; <🎜>
Unset($array[$key]); <🎜>
Return $element; <🎜>
} <🎜>
?>
http://www.bkjia.com/PHPjc/631310.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/631310.htmlTechArticleA simple array_push() function usage, this is a commonly used function for array operations, friends in need You can refer to (PHP 4, PHP 5) array_push to push one or more units...
|
|
|