Jon R - 5 months ago 30

PHP Question

Is there a straightforward way in PHP to combine multiple arrays together but respect the relative order of the elements?

So for example if I had two arrays

`$x = ('1','2','3','4');`

and

`$y = array('a','b','c','d','e');`

and I wanted combine them into a single array

`$z = ('1','a','2','b','3','c','4','d','e');`

Is there a straightforward way of doing this? The ideal solution would also account for different lengths of arrays, behaving as my example does.

array_merge doesn't seem to achieve what I want as it just appends one array to the other.

My current solution loops through each array in order and pushes values to my $z array. This is not only inelegant, it also requires the input arrays to have the same number of values, which isn't ideal for my application.

Any insight would be appreciated

Answer

You could use this generic function, which can accept any number of arrays, and will output an array with the elements taken from the first "column" first, then from the second, etc:

```
function mix_merge(...$args) {
return call_user_func_array('array_merge',
array_map(function($i) use ($args) { return array_column($args, $i); },
range(0, max(array_map('count', $args))-1)));
}
// Sample data:
$x = array('1','2','3','4');
$y = array('a','b','c','d','e');
$z = array('A','B','C');
$res = mix_merge($x, $y, $z);
```

Result array will be:

```
['1', 'a', 'A', '2', 'b', 'B', '3', 'c', 'C', '4', 'd', 'e']
```