There are two arrays:
JavaScript
x
$arrOne = [1, 3, 4];
$arrTwo = [2, 5,];
$newArr = [];
How to merge to get like this;
$newArr = [1, 2, 3, 4, 5];
Now displays through one, this option is not suitable.
JavaScript
foreach ($arrOne as $k => $v) {
$newArr[] = $v;
$newArr[] = $arrTwo[$k];
}
Here is another example. Tthe values can be different in the array.
JavaScript
$arrOne = [154, 32, 15];
$arrTwo = [682, 124,];
Again for this example it is necessary that the values from the second array always be at 2 and 5 positions in the new array:
JavaScript
$newArr = [154, 682, 32, 15, 124];
Advertisement
Answer
You can use array_splice to merge the arrays in the intended way to the specific indices:
JavaScript
array_splice( $arrOne, 1, 0, $arrTwo[0]);
array_splice( $arrOne, 4, 0, $arrTwo[1]);
var_dump($arrOne);
Demo 1:
Using original data:
JavaScript
$arrOne = [1, 3, 4];
$arrTwo = [2, 5,];
Demo 2:
Using second set of data:
JavaScript
$arrOne = [154, 32, 15];
$arrTwo = [682, 124,];