PHP array_shift()Function
Complete PHP Array Reference Manual
Examples
Remove the first element of an array (red), and return the removed element:
$a=array("a"=>"red","b"=>"green","c"=>"blue");
echo array_shift($a);
print_r ($a);
Run example »
Definition and Usage
The array_shift() function removes the first element from an array and returns the removed element.
Note:If the keys are numeric, all elements will get new keys, starting from 0 and incrementing by 1 (see example below).
Syntax
array_shift(array)
| Parameter | Description |
|---|---|
| array | Required. Specifies the array. |
Technical Details
| Return value: | Returns the value of the removed element from the array, or NULL if the array is empty. |
|---|---|
| PHP Version: | 4+ |
More Examples
Example 1
Using numeric keys, all elements will get new keys:
$a=array(0=>"red",1=>"green",2=>"blue");
echo array_shift($a);
print_r ($a);
Run example »
If you want to preserve the numeric key indices, you can use the following method:
Example
<?php
$arr = array('1'=>1,'2'=>2,'3'=>'3');
function array_kshift(&$arr)
{
list($k) = array_keys($arr);
$r = array($k=>$arr[$k]);
unset($arr[$k]);
return $r;
}
array_kshift($arr);
print_r($arr);
?>
$arr = array('1'=>1,'2'=>2,'3'=>'3');
function array_kshift(&$arr)
{
list($k) = array_keys($arr);
$r = array($k=>$arr[$k]);
unset($arr[$k]);
return $r;
}
array_kshift($arr);
print_r($arr);
?>
The output of the above example is:
Array
(
[2] => 2
[3] => 3
)
More content:PHP Remove the first element of an array
Complete PHP Array Reference Manual Other extensions