How to remove the first element of an array using PHP and then storing the element in a variable

Written by Ian Carnaghan · 29 sec read >
  • By using the PHP function ‘array_shift‘ we can remove the first value of an array
    • array_shift – Shift an element off the beginning of array (PHP 4 & 5)


$array = array("apple","peach","pineapple","banana");
$first_element = array_shift($array);

echo '<pre>';
echo '</pre>';

echo $first_element;

In the above example we have an array with 4 values, now using the ‘array_shift‘ function we remove the first value namely apple and store it in the $first_element variable.

Now if we print the contents of $array we’ll notice there are only 3 values left namely peachpineapple and banana and apple belongs to the $first_element variable.

Output from example:

//Contents of $array
    [0] => peach
    [1] => pineapple
    [2] => banana

//Value of First Element

Last Updated On March 22, 2018
Written by Ian Carnaghan
I am a software developer and online educator who likes to keep up with all the latest in technology. I also manage cloud infrastructure, continuous monitoring, DevOps processes, security, and continuous integration and deployment. Profile

Leave a Reply

Notify of