AppDividend
Latest Code Tutorials

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.

Syntax

See the syntax of PHP array_shift() function.

array_shift(array)

Arguments

An array parameter is required, and it specifies an array.

Example

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.

PHP Array Shift Example

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.

array_shift() function in Associative Array

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.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.