How to interpolate two arrays?

I have two arrays:

A = [1, 2, 3, 4] B = ['a', 'b', 'c', 'd'] 

I want to combine them into tuples (A, B) in a one-dimensional array:

 C = [1, 'a', 2, 'b', 3, 'c', 4, 'd'] 

Is there any native function in PHP that allows you to interpolate two arrays this way? If not, can the loop be the most efficient and effective way to do this?

The number of elements A will always be the same for B.

Note. If this helps, in the context of my specific needs, array A can be summed as one 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'] 
+4
source share
4 answers

I don’t know if there is a built-in matching function that makes it easier, but it is a simple, naive implementation.

 $a = array(1,2,3,4); $b = array('a','b','c','d'); function array_interpolate($a, $b) { if (sizeof($a) != sizeof($b)) throw new Exception('Arrays must be of same size'); $result = array(); for ($i = 0, $l = sizeof($a); $i < $l; $i++) { $result[2*$i] = $a[$i]; $result[2*$i+1] = $b[$i]; } return $result; } $res = array_interpolate($a, $b); print_r($res); 

The above returns

 Array ( [0] => 1 [1] => a [2] => 2 [3] => b [4] => 3 [5] => c [6] => 4 [7] => d ) 
+3
source

In this case, the loops are fine, since PHP does not have a built-in function for interleaving 2 arrays, but this is a good 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; } 
+4
source
 $C = call_user_func_array('array_merge', call_user_func_array('array_map', array(NULL, $A, $B))); 
+2
source

Since in PHP arrays are implemented as hash tables ( a hash table on wikipedia ), you will not be able to reach your goal faster through a loop through the array.

Here is a simple example:

 function interpolate(array $a,array $b) { $result = array(); for($i = 0; $i < count($a); $i++) { $result[] = $a[$i]; $result[] = $b[$i]; } return $result; } 
+1
source

Source: https://habr.com/ru/post/1494800/


All Articles