PHP array_shift() Function

PHP array_shift() function is used to remove the first element from an array and returns the value of the removed element.

Syntax

array_shift(array)

Parameters

array(required): It specifies an array.

Return value

This function returns the value of the shifted element from the array. Otherwise, null if the array is empty.

Visual Representation
 Visual Representation of PHP array_shift() Function

Example 1: How to Use array_shift() function

<?php

$data = ['Apple', 'Microsoft', 'Amazon', 'Alphabet', 'Facebook'];

echo "Original Array: " ;

print_r($data);

echo "Removed element: ";

echo array_shift($data)."\n";

echo "Updated Array : \n";

print_r($data);

Output

Original Array: Array
(
 [0] => Apple
 [1] => Microsoft
 [2] => Amazon
 [3] => Alphabet
 [4] => Facebook
)

Removed element: Apple

Updated Array : 
Array
(
 [0] => Microsoft
 [1] => Amazon
 [2] => Alphabet
 [3] => Facebook
)

In this example, the first element (“Apple“) of the $data array is removed and returned. 

Example 2: Using Associative Array

<?php

$data = ['a' => 'Apple', 'b' => 'Microsoft', 
         'c' => 'Amazon', 
         'd' => 'Alphabet',
         'e' => 'Facebook'];

echo array_shift($data)."\n";

print_r($data);

Output

Original Array: Array
(
 [a] => Apple
 [b] => Microsoft
 [c] => Amazon
 [d] => Alphabet
 [e] => Facebook
)

Removed element: Apple

Updated Array : 
Array
(
 [b] => Microsoft
 [c] => Amazon
 [d] => Alphabet
 [e] => Facebook
)

That’s it.

Leave a Comment

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