PHP Remove the First Element of an Array Using a Functionarray_shift()
Example
<?php
$stack = array("orange", "banana", "apple", "raspberry");
$fruit = array_shift($stack);
print_r($stack);
?>
$stack = array("orange", "banana", "apple", "raspberry");
$fruit = array_shift($stack);
print_r($stack);
?>
The output of the above example is:
Array
(
[0] => banana
[1] => apple
[2] => raspberry
)
array_shift() removes the first element of array and returns it as the result, reduces the length of array by one and moves all other elements forward by one. All numeric keys will be changed to start counting from zero, while string keys will remain unchanged.
Example
<?php
$arr = array('a'=>1,'b'=>2,'c'=>'3');
array_shift($arr);
print_r($arr);
$arr2 = array('1'=>1,'2'=>2,'3'=>'3');
array_shift($arr2);
print_r($arr2);
?>
$arr = array('a'=>1,'b'=>2,'c'=>'3');
array_shift($arr);
print_r($arr);
$arr2 = array('1'=>1,'2'=>2,'3'=>'3');
array_shift($arr2);
print_r($arr2);
?>
The output of the above example is:
A
Array
(
[b] => 2
[c] => 3
)
Array
(
[0] => 2
[1] => 3
)
If you want to preserve the numeric key indexes, 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
)