W3jar
154 words
1 minutes

How to Add Elements to the Beginning of a PHP Array

2024-08-23

In PHP, if you want to add elements to the beginning of an array, you can use the array_unshift() function. This function takes the array you want to modify as its first argument, followed by the elements you want to add. Here’s how you can use it:

Syntax#

array_unshift(array &$array, mixed ...$values): int
  • $array: The array to which you want to add elements.
  • $values: The elements you want to add to the beginning of the array.

Example#

<?php
// Initial array
$fruits = array("banana", "orange", "apple");

// Add elements to the beginning
array_unshift($fruits, "strawberry", "blueberry");

// Print the modified array
print_r($fruits);
?>

Output#

Array
(
    [0] => strawberry
    [1] => blueberry
    [2] => banana
    [3] => orange
    [4] => apple
)

Explanation#

In the example above:

  • $fruits is the initial array.
  • array_unshift() adds "strawberry" and "blueberry" to the beginning of the $fruits array.
  • print_r($fruits) outputs the array with the new elements at the start.

Using array_unshift() is straightforward and effective for prepending elements to an array in PHP.