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

PHP 8.4 released the array_any to test if at least one element matches a condition. Understand the array_any Function in…

PHP Type Casting: How to Convert Variables in PHP

Type casting in PHP refers to the process of converting a variable from one data type to another. This is…

PHP array_fill Function: Fill Array with Same Value

You can use the array_fill function in PHP when you must fill an array with one value. You may want…

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 XML Expat Parser: A Complete Guide

If you've ever tried to pull data from an XML file, you know it can be a bit tricky at…

PHP filter_var_array: How to Validate Multiple Inputs

The filter_var_array() appeared to make input validation simple and sanitization in PHP. It handles multiple inputs with different filters was…

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 strlen Function: How It Works with Strings

Developers needed a way to check the length of a string, so the strlen function was introduced to handle this…

PHP is_file Function: Check if a File Exists

If you are working with PHP and need a way to confirm if something is indeed a file, the is_file function will…

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…

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.