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

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

Barbara Streisand
Barbara StreisandOriginal
2024-11-02 00:09:02192browse

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

Inserting an Item at the Beginning of an Array in PHP

Inserting an element into an array at the end is a simple task, accomplished using the array append operator. However, when you need to insert an item at the beginning of the array, a different approach is required.

Array_unshift()

To insert an item at the beginning of an array in PHP, we utilize the array_unshift() function. This function allows us to insert one or more elements at the start of an array.

Syntax:

<code class="php">array_unshift($array, $item1, $item2, ..., $itemN);</code>

where:

  • $array is the array to be modified
  • $item1, $item2, ..., $itemN are the items 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, the item 'item1' is now the first element in the array.

Conclusion:

Array_unshift() provides a convenient way to insert items at the beginning of an array in PHP. Remember this function when you need to prepend elements to your arrays.

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