array_shift() and array_unshift()
Learn to remove from the start with array_shift() and add to the start with array_unshift().
array_shift() and array_unshift()
array_shift() removes the first element of an array and returns it. The remaining elements are re-indexed. For example, on $q = ["Ali", "Ayşe"];, array_shift($q) returns "Ali" and $q becomes ["Ayşe"].
array_unshift() adds one or more elements to the start. array_unshift($q, "Veli") puts "Veli" at the front. Together they form a queue: the first item in is the first one out.
Not a stack, a queue
array_shift() and array_unshift() form a queue pattern. In a queue, the first item added is the first one processed; this is called FIFO (first in, first out).
They are not the same as array_push() and array_pop(): push/pop work on the end of the array, while shift/unshift work on the start. Also, array_shift() returns the removed element, while array_unshift() returns the new count.
Exercise Build a queue and shift from the start
Define a $queue array and start it empty []. Use array_unshift() to add three values to the start in one call, in this order: "Alex", "Maya", "Sam". Then use array_shift() to assign the first element to $first and print it with echo $first . "\n".
Show example solution
First add with array_unshift($queue, "Alex", "Maya", "Sam");. Then take the first with $first = array_shift($queue); and print echo $first . "\n";.
Example solution:
<?php
$queue = [];
// Add to the queue, take the first and print
array_unshift($queue, "Alex", "Maya", "Sam");
$first = array_shift($queue);
echo $first . "\n";
Test yourself
-
What is the output of the code below?
$names = ["Ali", "Ayşe", "Mehmet"]; $first = array_shift($names); echo $first;- Ali
- Ayşe
- Mehmet
- null
Show answer
Ali — Correct. array_shift returns the first element; that is 'Ali'.
-
Write the function to add to the start
$queue = ["Ali", "Ayşe"]; ____($queue, "Veli"); print_r($queue);Show answer
$queue = ["Ali", "Ayşe"]; array_unshift($queue, "Veli"); print_r($queue); -
Match each function to its end
- array_push
- Adds to the end
- array_pop
- Removes from the end
- array_shift
- Removes from the start
- array_unshift
- Adds to the start
-
What does array_unshift return?
- The removed item
- The first item
- The added item
- The new count
Show answer
The new count — Correct. array_unshift returns the new count.