PHP array_shift: Remove the First Array Element with Examples

php array shift

The array_shift function in PHP takes the first element from an array and returns it. It also moves all other elements down by one position. The original array changes because array_shift works directly on it.

Understand the array_shift Function in PHP

The array_shift is a built-in function used to remove and return the first value from an array. The array changes in place and loses one element from the start.

It can handle both indexed arrays and associative arrays.

Here is the syntax:

array_shift(&$array)

The $array used to modify and remove its first element.

PHP finds the first element in memory when you call array_shift. It stores that value for the return. Then it shifts every element key down by one position for indexed arrays.

Here is a quick example:

$data = [10, 20, 30];
$first = array_shift($data);

echo $first; // 10
print_r($data); // [20, 30]

For associative arrays, it removes the first key-value pair. That doesn’t need to re-index the keys.

For example:

$user = [
    "name" => "Ali",
    "age" => 25,
    "city" => "Jeddah"
];

$firstValue = array_shift($user);

echo $firstValue; // Ali
print_r($user);
/*
Array
(
    [age] => 25
    [city] => Jeddah
)
*/

Here, it removes the “Ali” field. The remain array still has age and city keys unchanged

The Difference Between array_shift and array_pop

The array_shift deletes and returns the first element of an array while the array_pop removes and returns the last element of an array.

Here are the key differences:

Featurearray_shiftarray_pop
Removes element fromStart of arrayEnd of array
Yes, for indexed arraysYes for indexed arraysNo re-index
Affects associative keysKeeps keys after first removedKeeps keys after last removed

You can choose array_shift when you need the first value. But the array_pop when you need the last value.

Examples array_shift in PHP

Remove the first value from a numeric array:

$nums = [5, 10, 15, 20];
$first = array_shift($nums);

echo $first; // 5
print_r($nums);

This code takes 5 from the array and returns it. The rest of the numbers remain in the array with their positions shifted.

The output:

5
Array
(
[0] => 10
[1] => 15
[2] => 20
)

Get the first task from a list and process it:

$tasks = ["Write report", "Send email", "Prepare sheets"];
$currentTask = array_shift($tasks);

echo "Processing: " . $currentTask;

This code removes the first task "Write report" and shows it. The array now has the other tasks, which allow it to wait in order.

The output:

Processing: Write report

Use array_shift with nested arrays:

$data = [
    ["id" => 1, "value" => "A"],
    ["id" => 2, "value" => "B"],
    ["id" => 3, "value" => "C"]
];

$firstRow = array_shift($data);
print_r($firstRow);

This code removes the first sub-array with "id" => 1. It returns the removed row and leaves the rest for later use. The output:

Array
(
[id] => 1
[value] => A
)

Combine array_shift with a loop:

$queue = ["Job1", "Job2", "Job3"];

while (!empty($queue)) {
    $job = array_shift($queue);
    echo "Run: $job\n";
}

This code runs through each job in the queue. It always takes the first one until no jobs remain in the list.

The result:

Run: Job1
Run: Job2
Run: Job3

Wrapping Up

In this article, you learned how array_shift removes the first element and how it works with both indexed and associative arrays.
You also saw how it differs from array_pop and how to use it in real cases.

Here is a quick recap:

  • array_shift removes from the start.
  • It re-indexes numeric arrays.
  • It works on associative arrays and doesn’t change keys.

FAQs

What is the use of array_shift in PHP?

$fruits = ['apple', 'banana', 'cherry'];
$first = array_shift($fruits);
print_r($fruits); // ['banana', 'cherry']
echo $first; // apple
It removes the first element from the array and returns it.

How does array_shift work with associative arrays?

$user = ['name' => 'John', 'age' => 25];
$first = array_shift($user);
print_r($user); // ['age' => 25]
echo $first; // John
It removes the first key-value pair based on internal order.

What is the difference between array_shift and array_pop?

$arr = [1, 2, 3];
array_shift($arr); // removes 1 from start
array_pop($arr); // removes last element
array_shift removes from the beginning, array_pop removes from the end.

Similar Reads

PHP AND (&&) Operator: Usage & Examples

As you are entering into PHP, it would be essential to understand how logical operators work. The PHP AND operator…

PHP While Loop: Iterating Through Code Blocks

The PHP “while” loop is a simple tool that repeatedly runs a block of code as long as a certain…

Understanding the Increment and decrement operators in PHP

The increment and decrement are operators that can be used to increase or decrease the variable values which have a…

PHP abs Function: How to Get Absolute Values

The abs() function in PHP gives you a number without its sign — it always returns a positive value. That…

PHP Elvis Operator: How (?:) Works with Examples

The Elvis operator in PHP is a shorthand version of the ternary operator. PHP allows developers to use this conditional…

PHP Multidimensional Arrays: Data Manipulation

In web development, managing and manipulating data is one of the most common tasks. When it comes to storing complex…

PHP filter_var_array: How to Validate Multiple Inputs

The filter_var_array() appeared to make input validation simple and sanitization in PHP. It handles multiple inputs with different filters was…

PHP compact Function: Assoc Array from Variables

The PHP compact function is a way to pull variables into an array. In this article, you will learn how…

Understanding the PHP Enumerable

Actually, the PHP enumerable is a new feature of 8.1 which allows you to define a new type. This feature…

PHP array_diff_uassoc: How to Compare Arrays with Keys

PHP array_diff_uassoc compares arrays by values and keys. You can also pass a custom function to compare keys in your…

Previous Article

HTML ins Tag: How to Mark Inserted Text in a Document

Next Article

JavaScript Object References and Copying for Beginners

Write a Comment

Leave a Comment

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


Subscribe to Get Updates

Get the latest updates on Coding, Database, and Algorithms straight to your inbox.
No spam. Unsubscribe anytime.