Home >Backend Development >PHP Tutorial >How do I insert an item at the beginning of an array in PHP?

How do I insert an item at the beginning of an array in PHP?

Barbara Streisand
Barbara StreisandOriginal
2024-11-02 12:20:02588browse

How do I insert an item at the beginning of an array in PHP?

Insert an Item at the Beginning of an Array in PHP

Inserting items to the end of an array is straightforward using $arr[] = $item. However, to insert an item at the beginning of an array, a different approach is required.

Solution: array_unshift()

To insert an item at the beginning of an array in PHP, use the array_unshift($array, $item) function. This function takes two arguments: the target array and the item to insert.

Example:

<code class="php">$arr = array('item2', 'item3', 'item4');
array_unshift($arr , 'item1');
print_r($arr);</code>

Output:

Array
(
 [0] => item1
 [1] => item2
 [2] => item3
 [3] => item4
)

As you can see, item1 has been successfully inserted at the beginning of the array, shifting the original elements to the right.

The above is the detailed content of How do I insert an item at the beginning of an array in PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn