Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to interpolate two arrays?

Tags:

arrays

php

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']
like image 304
Renato Rodrigues Avatar asked Dec 25 '22 23:12

Renato Rodrigues


1 Answers

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;
}
like image 103
cschorn Avatar answered Jan 12 '23 16:01

cschorn