PHP Array Shift Example | PHP array_shift() Function Tutorial
PHP array_shift() is an inbuilt function that removes the first element from an array and returns the value of a removed item. 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 Example
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. It sped up as an array shrank, as it has to reindex 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 the removal of a 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, then you can use the array_shift() function.
Finally, PHP Array Shift Example | PHP array_shift() Function Tutorial is over.