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 MySQL CRUD: Understanding Database Operations

PHP and MySQL have become an inseparable pair for web developers. One handles the logic, while the other stores the…

PHP Arrow Functions: Understanding “fn” Syntax

Arrow functions were introduced in PHP 7.4. They offer you a way to write simple operations, such as calculations, filters,…

PHP Hello World: Write Your First Program with Code Example

You always start with “Hello World” when you learn a new language. It keeps things simple. You see right away…

PHP filter_list(): List Available Filters

PHP introduces the filter_list() function to give developers a way to check all available filters in the filter extension. This…

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 array_multisort Function with Examples

PHP array_multisort sorts many arrays or a multi level array in one go. It can sort data in numeric order…

How to Remove the Last Character from a String in PHP

You may need to cut the last character from a string if it shows by mistake in PHP. That may…

PHP array_column: How to Extract Values from Arrays

The array_column function in PHP takes values from one column in a multidimensional array. You can use it to pull…

PHP MySQL Create Database: MySQLi & PDO Examples

If you are working with PHP and MySQL, one of the first tasks you may need is to create a…

PHP Variable Basics: Everything You Need to Know

Think about the PHP variable as little storage boxes holding your data, whether it is a number, a word, or…

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.