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

  • 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

Image Credits: Photo by Isis França on Unsplash.

More Similar Posts

No results found.