PHP | array_shift() Function

This inbuilt function of PHP removes the first element from an array and returns the value of the removed element. After the removal of the first element, the key of the remaining elements is modified and again re-numbered from the start, only if the keys are numerical. In other words, this function basically shifts an element off from the beginning in an array.

Syntax:

array_shift($array)

Parameters: The function takes only one argument, $array which refers to the original input array which needs to be shifted.



Return Value: As already mentioned, the function returns the value of the shifted element from the array, otherwise NULL if the array is empty.

Examples:

Input : $array = ("ram"=>2, "aakash"=>4, "saran"=>5, "mohan"=>100)
Output : 2

Input : $array = (45, 5, 1, 22, 22, 10, 10);
Output :45

In this program, we will see how the function works in key_value pair array.

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
// PHP function to illustrate the use of array_shift()
function Shifting($array)
{
    print_r(array_shift($array));
    echo "\n";
    print_r($array);
}
$array = array("ram"=>2, "aakash"=>4, "saran"=>5, "mohan"=>100);
Shifting($array);
?>

chevron_right


Output:

2
Array
(
    [aakash] => 4
    [saran] => 5
    [mohan] => 100
)

Now let’s see how the function takes care of the default key.

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
// PHP function to illustrate the use of array_shift()
function Shifting($array)
{
    print_r(array_shift($array));
    echo "\n";
    print_r($array);
}
$array = array(45, 5, 1, 22, 22, 10, 10);
Shifting($array);
?>

chevron_right


Output:

45
Array
(
    [0] => 5
    [1] => 1
    [2] => 22
    [3] => 22
    [4] => 10
    [5] => 10
)

Reference:
http://php.net/manual/en/function.array-shift.php



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : Akanksha_Rai



Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.