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

H

How Can We Help?

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)

Example:

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

echo '<pre>';
print_r($array);
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
Array
(
    [0] => peach
    [1] => pineapple
    [2] => banana
)

//Value of First Element
apple

About the author

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.

About Author

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.

Follow Me