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 array_key_exists: How it Works with Examples

The PHP array_key_exists function checks a given key in an array and tells if that key exists or not. Understand…

How to Insert Multiple Rows in MySQL with PHP?

Inserting multiple data rows using PHP is a basic task. However when you start working with MySQL databases, So that…

PHP trim(): How to remove Whitespace from String

Early PHP scripts often failed because of extra spaces or line breaks in strings. These issues came from user input…

PHP Ternary Operator: How to Write Short Expressions

The PHP ternary operator gives you a way to write short expressions. It reduces lines of code and avoids long…

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…

IF-Else: Executes the IF-Else Statement in PHP

Programming is all about choices. Everything you do in code boils down to answering a question: What should happen if…

PHP $_SESSION: Secure Your Web Applications in PHP

It’s very important to remember user data for each session when building web applications. This enables a high level of…

PHP array_all Function: How it Works with Examples

PHP 8.4 released a new built-in function, array_all checks to check if all array values meet a condition. It gives…

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 Multidimensional Arrays: Data Manipulation

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

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.