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 if-elseif Statement: ‘elseif’ versus ‘else if’

PHP’s if-elseif statement is a fundamental construct that allows developers to control the flow of their code based on different conditions. In…

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…

MongoDB PHP Driver: Install and Get Started

Traditional relational databases like MySQL often take center stage. However, with the rise of NoSQL databases, MongoDB has emerged as…

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 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 Comparison Operators Guide with Examples

PHP comparison operators allow you to compare values in many ways, and this simplifies the process of checking whether values…

PHP Assign Function to Variable – Examples and Explanation

PHP variable function is a variable that is used to assign a function name with parentheses (). However, the PHP interpreter…

PHP Bitwise Operators: AND, OR, XOR, NOT with Examples

Bitwise operators use symbols like &, |, and ^, and they work at the binary level. But once you understand…

How to Use PHP count() to Get Array Length

PHP developers may be need to determine the number of elements in an array. The count() function in PHP makes…

How to Update Documents in MongoDB Using PHP

Updating documents in MongoDB with PHP involves using the updateOne or updateMany methods from the MongoDB PHP library. These methods allow for precise updates,…

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.