Coding Triumph

Helpful code snippets & tutorials

How to insert an element at the beginning of an array in PHP

There are two types of arrays in PHP: indexed arrays and associative arrays. In this post, I’ll show you how you can insert an item at the beginning of both types. Let’s start with indexed arrays.

1. Indexed arrays:

There are two ways we can use to insert one or more elements at the beginning of an indexed array: the array_unshift() function or the spread operator since PHP 7.4.

$animals = array("dog", "fox", "lion");
 
# with the array_unshift() function
array_unshift($animals, "parrot", "cat");

# with the spread operator
$animals = ["parrot", "cat", ...$animals];

# print the result
print_r($animals);
/**
* Array
* (
*     [0] => parrot
*     [1] => cat
*     [2] => dog
*     [3] => fox
*     [4] => lion
* )
*/

2. Associative arrays:

In the case of an associative array, you can use either the union operator or the array_merge() function.

$array = ['c' => 3, 'd' => 4, 'f' => 5];

# the union operator
$new_values = ['a' => 1, 'b' => 2];
$new_array = $new_values + $array;

# the array_merge() function
$new_values = ['a' => 1, 'b' => 2];
$new_array = array_merge($new_values, $array);

# print the result
print_r($new_array);
/**
* Array
* (
*     [a] => 1
*     [b] => 2
*     [c] => 3
*     [d] => 4
*     [f] => 5
* )
*/

Conclusion:

Depending on the type of the array, I’ve given you multiple ways with which you can insert one or multiple values at the beginning of an array in PHP.

If you like this post, please share
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments