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

Barbara Streisand
Release: 2024-11-02 12:20:02
Original
513 people have browsed it

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

Output:

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

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!

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