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

66
May 27, 2022, at 09:00 AM

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];
``````

You can use array_splice to merge the arrays in the intended way to the specific indices:

``````array_splice( \$arrOne, 1, 0, \$arrTwo[0]);
array_splice( \$arrOne, 4, 0, \$arrTwo[1]);
var_dump(\$arrOne);
``````

Demo 1:

Using original data:

``````\$arrOne = [1, 3, 4];
\$arrTwo = [2, 5,];
``````

https://3v4l.org/dAMav

Demo 2:

Using second set of data:

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

https://3v4l.org/Xhl3K

You can use array_merge and sort functions to achieve this as following:

``````\$newArr = array_merge(\$arrOne, \$arrTwo);  // it will be [1, 3, 4, 2, 5]
sort(\$newArr); // it will sort array [1, 2, 3, 4, 5]
``````

You can use \$newArr now which have sorted data

``````\$arrOne = [1, 3, 4];
\$arrTwo = [2, 5];
\$newArr = [];
foreach(\$arrOne as \$key => \$one) {
switch(\$key) {
case 1:
\$newArr[] = \$arrTwo[0];
break;
case 4:
\$newArr[] = \$arrTwo[1];
break;
}
\$newArr[] = \$one;
}
if(count(\$newArr) < 5) {
\$newArr[] = \$arrTwo[1];
}
``````

Here we are considering there will be always two elements in second array

``````\$arrayOne = [12,23,45,56,65,78,99];
\$arrayTwo = [2,5];
\$mergedArray = [];
foreach(\$arrayOne as \$key => \$value) {

\$position = \$key + 1;
if (\$position === 2) {
\$mergedArray[] = \$arrayTwo[0];
} else if (\$position === 4) {
\$mergedArray[] = \$arrayTwo[1];
}
\$mergedArray[] = \$value;
}
``````
POPULAR ONLINE

### Add proc_open \$pipe inputs on the go dynamically

I am trying to create a C program compiler + executer using PHP

54

### How to keep the ?error on url if page extension not included?

I was able to remove thephp or

36

### Drupal 8 Entity Query - Condition for an unlimited fields

With Drupal QueryInterface, it's possible to add a condition on the delta itself by using '%delta' like this :

58

### Ho to proper enqueue asset in WP?

I have a question and I hope you can help meI am an amateur (quite clear :-) ) trying to enqueue some script

42