![]() |
VOOZH | about |
New item in an array can be inserted with the help of array_splice() function of PHP. This function removes a portion of an array and replaces it with something else. If offset and length are such that nothing is removed, then the elements from the replacement array are inserted in the place specified by the offset.
array array_splice ($input, $offset [, $length [, $replacement]])This function takes four parameters out of which 2 are mandatory and 2 are optional:
It returns the last value of the array, shortening the array by one element. Note that keys in replacement array are not preserved. Program
Original array : 1 2 3 4 5 After inserting 11 in the array is : 1 2 11 3 4 5
Time Complexity: O(n)
Auxiliary Space: O(1)
To insert a new item into an array at any position in PHP without using `array_splice()`, use `array_slice()` to split the array at the insertion point, then `array_merge()` to concatenate the parts with the new item inserted in between. This method maintains array integrity and flexibility.
Example: This example shows the implementation of the above-mentioned approach.
Array ( [0] => apple [1] => orange [2] => banana [3] => cherry )
Manual array manipulation involves iterating through an array, conditionally inserting or modifying elements, and reconstructing the array. This approach provides flexibility but requires careful handling of array indices and potentially higher complexity compared to built-in functions like array_splice() or array_merge().
Example
Array ( [0] => apple [1] => orange [2] => banana [3] => cherry )
References :https://www.php.net/manual/en/function.array-splice.php