← Back to Chapters

PHP array_shift() & array_unshift()

? PHP array_shift() & array_unshift()

? Quick Overview

PHP provides two useful functions for working with the beginning of arrays: array_shift() and array_unshift(). These functions allow you to remove and add elements to the beginning of an array, respectively.

? Key Concepts

  • array_shift() removes the first element of an array
  • array_unshift() adds elements to the start of an array
  • Both functions modify the original array

? Interactive Simulator

Visualize how the array changes and re-indexes.

 

? Syntax / Theory

? View Code Example
// Removes and returns the first element of the array
array_shift($array);

// Adds one or more elements to the beginning of the array
array_unshift($array, $value1, $value2);

? Code Example: array_shift()

? View Code Example
// Removing the first element from the array
<?php
$fruits = array("Apple", "Banana", "Cherry");
$removed = array_shift($fruits);
echo $removed;
print_r($fruits);
?>

? Explanation

The function removes Apple from the beginning of the array and returns it. The remaining array elements are reindexed automatically.

? Code Example: array_unshift()

? View Code Example
// Adding elements to the beginning of the array
<?php
$fruits = array("Banana", "Cherry");
array_unshift($fruits, "Apple", "Mango");
print_r($fruits);
?>

? Explanation

The new elements are inserted at the front of the array, and the total element count increases accordingly.

? Use Cases

  • Queue implementation (FIFO)
  • Processing ordered datasets
  • Adding priority items dynamically

✅ Tips & Best Practices

  • Always store the return value of array_shift() if needed
  • Use these functions carefully in large arrays due to reindexing
  • Ideal for managing queue-like structures

? Try It Yourself

  • Remove the first student from a list using array_shift()
  • Add a priority task at the front using array_unshift()
  • Combine both functions to simulate a task queue