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 Escape Characters: How to Escape Special Characters

Escape characters appeared in PHP because some symbols in strings serve special purposes. For example, a quote can end a…

How to Connect PHP to MongoDB

Connecting PHP to MongoDB allows you to integrate database functionalities into your web applications. MongoDB is a NoSQL database that…

PHP strict_types: How the Strict Mode Works

If you want to write good PHP code, strict mode should be on your radar. Strict mode—activated by the command declare(strict_types=1); at…

PHP array_merge: Combine Multiple Arrays into One

You have two or more arrays. You want one. That is the problem array_merge solves in PHP. This function lets…

PHP $_COOKIE: Securely Store and Manage Data

Ever notice how some websites just seem to "know" you? That’s thanks to cookies! When you’re working with PHP, $_COOKIE becomes a…

PHP Type Hints: Ensuring Data Integrity

PHP-type hinting is something that keeps your code in check and helps your functions receive just the right types of…

PHP $_ENV: Manage Environment Variables

In this tutorial, we will explore a form of superglobal variable in PHP: $_ENV, which symbolizes how PHP reaches for…

PHP Callable & Callback: Pass a Function to Another

The callback in PHP lets you pass functions as arguments and reuse code. It helps you to control how tasks…

PHP mb_substr Function: How it Works with Examples

You may need to get part of a text when you work with text in PHP. The mb_substr gives you…

PHP Resource Type | How the get_resource_type() Works

In this tutorial, I will explain what does mean the PHP resource and we are going to cover all PHP…

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.