Tags
Asked 3 years ago
9 Jun 2021
Views 351
steave ray

steave ray posted

Insert new item in array on any position in PHP

Insert new item in array on any position in PHP
jabber

jabber
answered Apr 26 '23 00:00

In PHP, you can insert a new item into an array at any position using the array_splice() function. Here's an example of how to insert a new item into an array at a specific position:



// Define an array
$myArray = array("apple", "banana", "orange");

// Insert a new item "grape" at index 1
array_splice($myArray, 1, 0, "grape");

// Output the updated array
print_r($myArray);

In this example, we have an array $myArray containing three items. To insert a new item "grape" at index 1 (i.e., between "apple" and "banana"), we use the array_splice() function with the following parameters:

The first parameter is the array to modify ($myArray).
The second parameter is the index where the insertion should start (1 in this case).
The third parameter is the number of items to remove (0 in this case, since we're not removing any items).
The fourth parameter is the item to insert ("grape" in this case).
After calling array_splice(), the array $myArray will contain the updated items "apple", "grape", "banana", "orange".

Note that array_splice() modifies the array in place, so there's no need to assign the result back to the original variable. Also note that the second parameter (the index) can be negative, in which case the insertion starts from the end of the array.
Post Answer