AppDividend
Latest Code Tutorials

PHP Array Shift Example | PHP array_shift() Function Tutorial

0

PHP Array Shift Example | PHP array_shift() Function Tutorial is today’s topic. The array_shift() function removes the first element from an array, and return 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.

array_shift(array)

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);

The output is following.

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);

The output is following.

array_shift() function in Associative Array

 

Using array_shift over 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.

Leave A Reply

Your email address will not be published.

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