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>
Example:
Consider the following array:
<code class="php">$arr = array('item2', 'item3', 'item4');</code>
To insert 'item1' at the beginning of this array, use the following code:
<code class="php">array_unshift($arr, 'item1');</code>
After the operation, the updated array will be:
<code class="php">Array ( [0] => item1 [1] => item2 [2] => item3 [3] => item4 )</code>
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!