How to use PHP array Shift and Unshift functions?

In this tutorial, you will learn what are the PHP array shift and unshift functions, and how to use them.

PHP array_shift function

The PHP array_shift() function is used to remove the first element of an array.

This function takes an array as an argument (whose first element you want to remove), and it returns the removed element.

array_shift(array);
<?php
$names = ['Bob', 'Mark', 'John'];

$removedItem = array_shift($names);
echo "Removed - $removedItem \n";

print_r($names);
Removed - Bob  
Array
(
    [0] => Mark
    [1] => John
)

PHP array unshift function

The PHP array_unshift() function is used to insert new elements to the beginning of an array.

This function takes an array as the first argument and you can pass multiple values to the rest of the arguments, but at least one value is required.

This function returns the number of elements (including the new elements).

array_unshift(array, value1, value2, value3, ...);
<?php
$names = ['Bob', 'Mark', 'John'];

$el_count = array_unshift($names, 'Jane', 'Alen');
echo "Number of Elements - $el_count \n";

print_r($names);
Number of Elements - 5 
Array
(
    [0] => Jane        
    [1] => Alen        
    [2] => Bob
    [3] => Mark        
    [4] => John        
)

Leave a Reply

Your email address will not be published. Required fields are marked *