John Davidson

php - How to combine 2 arrays with the condition that 2 and 5 values will be from the second array?

0 comments
Message:


There are two arrays:


$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.


foreach ($arrOne as $k => $v) {
$newArr[] = $v;
$newArr[] = $arrTwo[$k];
}

Here is another example. Tthe values can be different in the array.


$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:


$newArr = [154, 682, 32, 15, 124]; 


My Answer:
One way to achieve this is by using a combination of array_splice and array_merge functions in PHP. Here's how you can do it:

php
$arrOne = [154, 32, 15];
$arrTwo = [682, 124];

// Insert values from $arrTwo at positions 2 and 5 in $arrOne
array_splice($arrOne, 1, 0, $arrTwo[0]);
array_splice($arrOne, 4, 0, $arrTwo[1]);

// Merge the two arrays
$newArr = array_merge($arrOne, $arrTwo);

print_r($newArr);


This code will output:

Array
(
[0] => 154
[1] => 682
[2] => 32
[3] => 15
[4] => 124
)


This way, you can combine the two arrays with the condition that the values at positions 2 and 5 will be from the second array.

Rate this post

3 of 5 based on 6272 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us