Easy Tutorial
❮ The Different This Super Embedded Engineer Require Skills ❯

PHP Remove the First Element of an Array

Category Programming Techniques

To remove the first element of an array in PHP, use the function array_shift().

Example

<?php
$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 from the array and returns it, reducing the array's length by one and moving all other elements forward by one position. All numeric keys will be renumbered starting from zero, while textual 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);
?>

The output of the above example is:

Array
(
    [b] => 2
    [c] => 3
)
Array
(
    [0] => 2
    [1] => 3
)

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);
?>

The output of the above example is:

Array
(
    [2] => 2
    [3] => 3
)

** Click to Share Notes

Cancel

-

-

-

❮ The Different This Super Embedded Engineer Require Skills ❯