How to Prepend an Item to a PHP Array?

Patricia Arquette
Release: 2024-11-03 08:26:03
Original
178 people have browsed it

How to Prepend an Item to a PHP Array?

Inserting an Item to the Front of a PHP Array

When working with arrays in PHP, it's common to want to add elements to the array. Typically, adding an item to the end of the array is straightforward using $arr[] = $item. However, inserting an item at the beginning of the array requires a different approach.

array_unshift(): The Key to Prepending

To insert an item at the beginning of an array in PHP, the array_unshift() function comes into play. This function allows you to prepend an item to the array, effectively moving all existing elements forward in the array.

Syntax:

<code class="php">array_unshift($array, $item);</code>
Copy after login

Example:

Consider the following array:

<code class="php">$arr = array('item2', 'item3', 'item4');</code>
Copy after login

To insert 'item1' at the beginning of this array, use the following code:

<code class="php">array_unshift($arr, 'item1');</code>
Copy after login

After the operation, the updated array will be:

<code class="php">Array
(
 [0] => item1
 [1] => item2
 [2] => item3
 [3] => item4
)</code>
Copy after login

Conclusion:

Using array_unshift() is a simple and effective way to insert an item at the beginning of an array in PHP. This technique is particularly useful when you need to maintain the order of elements or add an element as the first item in the array.

The above is the detailed content of How to Prepend an Item to a PHP Array?. 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