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

Patricia Arquette
Release: 2024-11-02 08:41:29
Original
504 people have browsed it

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

The output of this code will be:

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

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!

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!