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

Barbara Streisand
Release: 2024-11-02 00:09:02
Original
191 people have browsed it

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>
Copy after login

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>
Copy after login

Output:

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

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!