PHP array_unshift: How to Add Values to the Start of an Array

php array_unshift function

PHP array_unshift helps you add new elements to appear before the existing ones.

Understand the array_unshift function in PHP

The array_unshift in PHP adds one or more values to the start of an array and moves the old keys.

Here is the syntax:

array_unshift(&$array, $value1, ...$values)
  • $array — the target array
  • $value1 — the first value to add
  • $values — optional extra values to add after the first one

The function returns the new number of elements in the array after the values are added.

Here is a quick example:

$fruits = ["banana", "orange"];
array_unshift($fruits, "apple");
print_r($fruits);

The output:

Array
(
[0] => apple
[1] => banana
[2] => orange
)

This code adds "apple" to the start, and the rest of the array moves forward.

You can use this function when you want to keep the latest items at the start of the list or when you need to prepare ordered data with priority values first.

Use the array_unshift in PHP with Arrays

Add a Single Element to PHP array_unshift:

$numbers = [2, 3, 4];
array_unshift($numbers, 1);
print_r($numbers);

This code places the value 1 at the start and shifts the other numbers to the right.

Here is the output:

Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
)

Add Multiple Elements with PHP array_unshift:

$letters = ["c", "d"];
array_unshift($letters, "a", "b");
print_r($letters);

The code adds two values to the start in the same order you give them. The output:

Array
(
[0] => a
[1] => b
[2] => c
[3] => d
)

Use array_unshift with Indexed Arrays:

$colors = ["blue", "green"];
array_unshift($colors, "red");
print_r($colors);

The code adds a new color at the start of an indexed array before the old colors.

The output:

Array
(
[0] => red
[1] => blue
[2] => green
)

Use PHP array_unshift with Associative Arrays

$person = ["age" => 25];
array_unshift($person, "John");
print_r($person);

The function reindexes numeric keys but keeps string keys the same when it adds new values.

The output:

Array
(
[0] => John
[age] => 25
)

Use array_unshift with Mixed Data Types:

$data = [100, "apple"];
array_unshift($data, true, 3.14);
print_r($data);

The function works fine with data types in the same array. The output:

Array
(
[0] => 1
[1] => 3.14
[2] => 100
[3] => apple
)

Difference Between array_unshift and array_push

The array_unshift adds values to the start of an array. array_push adds values to the end of an array. Both return the new count of elements after the change.

Featurearray_unshiftarray_push
PositionAdds values at the startAdds values at the end
Key ChangesReindexes numeric keysKeeps numeric keys in order
Use CasePut important items firstAdd extra items after the old ones

Use case for array_unshift: Insert priority items in front. Use case for array_push: Extend the array by adding items at the end.

Examples of array_unshift in PHP

Add a Priority Task to a Task List:

$tasks = ["Write report", "Send email"];
array_unshift($tasks, "Fix urgent bug");
print_r($tasks);

This example places a new task at the top so that the most urgent task appears before others.

Here is the output:

Array
(
[0] => Fix urgent bug
[1] => Write report
[2] => Send email
)

Add Multiple New Students at the Start:

$students = ["Ali", "Sara"];
array_unshift($students, "Omar", "Lina");
print_r($students);

The example shows how to add more than one name in a single call to the function.

The output:

Array
(
[0] => Omar
[1] => Lina
[2] => Ali
[3] => Sara
)

Merge Old and New Orders with Priority for New Ones:

$orders = ["Order #3", "Order #4"];
array_unshift($orders, "Order #1", "Order #2");
print_r($orders);

This code puts older orders first so that they are processed before the later ones.

The output:

Array
(
[0] => Order #1
[1] => Order #2
[2] => Order #3
[3] => Order #4
)

Wrapping Up

In this article, you learned how array_unshift works and how to use it with different arrays. You also saw how it differs from array_push and how to apply it in real examples.

Here is a quick recap:

  • array_unshift adds values to the start of an array
  • You can add one or more values in a single call
  • It reindexes numeric keys but keeps string keys as they are
  • It works with mixed arrays. Also works with indexed and associative.
  • Use it when you need priority items at the start of a list

FAQs

How to use array_unshift in PHP to add items to array start?


$colors = array("blue", "green");
array_unshift($colors, "red");
print_r($colors);
This code adds "red" to the start of $colors array.

What is the difference between array_unshift and array_push ?


$items = array("pen", "pencil");
array_unshift($items, "eraser"); // Add at start
array_push($items, "marker");    // Add at end
print_r($items);
array_unshift adds values at the start, array_push adds at the end.

Can array_unshift add multiple elements at once?


$nums = array(3, 4);
array_unshift($nums, 1, 2);
print_r($nums);
Yes, array_unshift accepts multiple values separated by commas.

Similar Reads

PHP sizeof: How to Count Elements in Arrays with Examples

The sizeof function in PHP exists to help developers know how many items an array holds. Understand the sizeof Function…

PHP explode Function: How it Works with Examples

When you deal with text in PHP, sometimes you need to break it into parts. This is common when users…

PHP fread Function: How to Read Files in PHP

In some cases, you need to handle a lot of data or simply try to open a file, or read…

PHP require_once and require

Essentially, “require” and “require_once” are directives in PHP to include and evaluate a specific file during the execution of a…

PHP Assignment Operators: A Complete Guide

The assignment operators are the sets of gears that keep your code well-oiled and running when deep in PHP, allowing…

PHP List MongoDB Collections

Sometimes, you may need to list collections with MongoDB in a PHP environment to manage or analyze your database structure.…

PHP Spread Operator: Understand How (…) Syntax Works

Before the spread operator, PHP developers had to pass array items to a function using extra steps. They often had…

Mastering PHP’s Do-While Loop: Examples and Explanation

The PHP do-while loop is a type of loop that executes a block of code at least once, and then…

PHP str_replace Function: How it Works with Examples

If you find a word that does not fit and want to fix it. You can use the PHP str_replace…

PHP filter_var: Understand How to Sanitize Input

PHP didn’t have a way to check or clean user input. Developers used scattered code—some wrote custom checks, others used…

Previous Article

HTML samp Tag: How to Show Sample Program Output

Next Article

HTML Syntax for Beginners: How it Works with Examples

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.