How to use array_slice() Function In PHP
The array_slice() function can be used to split the array into two parts before and after the given element. The new element can then be inserted between these two parts.
Example: The array_slice() function splits the array at the position after 30, and array_merge() combines the two parts with 35 in between.
<?php
function insertElement($arr, $element,
$newElement) {
$pos = array_search($element, $arr);
if ($pos !== false) {
$before = array_slice($arr, 0, $pos + 1);
$after = array_slice($arr, $pos + 1);
return array_merge($before,
[$newElement], $after);
}
return $array;
}
$arr = [10, 20, 30, 40, 50];
$newArr = insertElement($arr, 30, 35);
print_r($newArr);
?>
Output
Array ( [0] => 10 [1] => 20 [2] => 30 [3] => 35 [4] => 40 [5] => 50 )
Insert a New Element After a Given Element in an Array in PHP
Given an array containing some elements, we want to insert a new item immediately after a specified element in the array. To insert a new element after a given element in an array, we need to locate the position of the given element and then insert the new element at the correct position.
Below are the approaches to insert a new element after a given element in an array in PHP:
Table of Content
- Using array_splice() Function
- Using foreach Loop
- Using array_slice() Function