How to Insert an Item into an Array at a Specific Position in PHP
Inserting a new element into an array at a specific position can be achieved using the array_splice function in PHP. This function allows for both insertion and removal of elements within an array.
To insert an item, provide the following parameters to array_splice:
For instance, the following code inserts the string "x" into the middle of the array $original:
$original = array('a', 'b', 'c', 'd', 'e'); $inserted = array('x'); array_splice($original, 3, 0, $inserted); // $original is now: array('a', 'b', 'c', 'x', 'd', 'e')
Note: If the replacement is a single element, you can omit the array brackets around it, unless the element itself is an array, object, or NULL.
Caution: The array_splice function modifies the original array in place and does not return the modified array. Therefore, it's important to assign the modified array to a new variable if you wish to preserve the original array.
The above is the detailed content of How to Insert an Item into a PHP Array at a Specific Index?. For more information, please follow other related articles on the PHP Chinese website!