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>
where:
Example:
<code class="php">$arr = array('item2', 'item3', 'item4'); array_unshift($arr, 'item1'); print_r($arr);</code>
Output:
Array ( [0] => item1 [1] => item2 [2] => item3 [3] => item4 )
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!