Home  >  Article  >  Backend Development  >  How to Insert an Item at the Beginning of an Array in PHP?

How to Insert an Item at the Beginning of an Array in PHP?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-02 08:41:29505browse

How to Insert an Item at the Beginning of an Array in PHP?

Inserting an Item at the Beginning of an Array in PHP

Inserting an item at the end of an array is straightforward using the array append operator ([]). However, inserting it at the beginning requires a different approach.

To insert an item at the beginning of an array, use the array_unshift() function. This function takes two parameters: the array to modify and the item to insert.

Here's an example:

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

The output of this code will be:

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

As you can see, 'item1' has been inserted at the beginning of the array.

The above is the detailed content of How to 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