I have two arrays:
A = [1, 2, 3, 4]
B = ['a', 'b', 'c', 'd']
I want to merge them into tuples (A, B) in an one-dimensional array:
C = [1, 'a', 2, 'b', 3, 'c', 4, 'd']
Is there some native function in PHP that lets you interpolate two arrays this way? If not, would a loop be the most effective and eficient way to do this?
The number of elements of A will always be the same of B.
Note: If it helps, in the context of my specific needs, array A can be summarized as a single value (since the value will be the same for all values in B).
A = 1
B = ['a', 'b', 'c', 'd']
C = [1, 'a', 1, 'b', 1, 'c', 1, 'd']
Loops are OK in this case, since PHP does not have a native function to interleave 2 arrays, but this is a nice way to solve the problem:
function interleave($array1, $array2) {
$result = array();
array_map(function ($e1, $e2) use (&$result) {
array_push($result, $e1, $e2);
}, $array1, $array2);
return $result;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With