Home > Backend Development > PHP Tutorial > How to Add an Element to the Beginning of an Array in PHP?

How to Add an Element to the Beginning of an Array in PHP?

Linda Hamilton
Release: 2024-11-03 22:23:30
Original
1021 people have browsed it

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

Output:

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

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!

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