"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Prepend an Item to a PHP Array?

How to Prepend an Item to a PHP Array?

Published on 2024-11-11
Browse:236

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:

array_unshift($array, $item);

Example:

Consider the following array:

$arr = array('item2', 'item3', 'item4');

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

array_unshift($arr, 'item1');

After the operation, the updated array will be:

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

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.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3