PHP Array Shift: How to remove first element of array in PHP
All the numerical array keys will be modified to start the counting from zero while the literal keys won’t be touched. If an array is empty, then the Null is returned.
PHP array shift
PHP array_shift() is a built-in function that removes the first element from an array and returns the value of a removed element. The array-shift() function accepts an array as an argument and returns the removed value.
See the syntax of PHP array_shift() function.
An array parameter is required, and it specifies an array.
See the below code example.
<?php // app.php $data = ['Apple', 'Microsoft', 'Amazon', 'Alphabet', 'Facebook']; echo array_shift($data)."\n"; print_r($data);
See the output.
An array_shift() function in Associative Array
See the following code example of an associative array.
<?php // app.php $data = ['a' => 'Apple', 'm' => 'Microsoft', 'b' => 'Amazon', 'c' => 'Alphabet', 'f' => 'Facebook']; echo array_shift($data)."\n"; print_r($data);
See the output.
Using array_shift over an enormous array was relatively slow. However, it sped up as an array shrank and reindexed a smaller data set.
For that purpose, you can use the array_reverse, then array_pop, which doesn’t need to reindex an array and will preserve the keys if you want it to.
The complexity of an array_pop() is O(1). The complexity of an array_shift() is O(n). An array_shift() requires a re-index process on the array, so it has to run over all the elements and index them.
After removing the first element, the key of the remaining items is modified and again renumbered from the start, only if the keys are numerical.
So, if you want to remove the first element from an array, you can use the array_shift() function.
That’s it for this tutorial.