Home > Article > Backend Development > How to Add an Element to the Beginning of an Array in PHP?
How to Prepend an Element to the Start of an Array in PHP
inserting an element to the end of an array in PHP is effortless using the syntax $arr[] = $item. However, inserting an element at the beginning of an array requires a different approach.
Solution: Utilizing array_unshift()
PHP provides the array_unshift() function tailored for this purpose. It takes two arguments: the array and the item to be inserted. The item is added to the beginning of the array, shifting the existing elements to the right.
Example
The following code demonstrates how to use array_unshift() to insert an element to the start of an array:
<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 )
This sample code modifies the $arr array by prepending 'item1' to the beginning. The resulting array now has 'item1' as its first element, followed by the original elements in their updated positions.
The above is the detailed content of How to Add an Element to the Beginning of an Array in PHP?. For more information, please follow other related articles on the PHP Chinese website!