Answer the question
In order to leave comments, you need to log in
How to beautifully/correctly combine values from two arrays, one of which is shorter?
There are two arrays:
$arr1 = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n']
$arr2 = [1, 2, 3, 4];
$result = ['a1', 'b2', 'c3', 'd4', 'e1', 'f2', 'g3', 'h4', 'i1', 'j2', 'k3', 'l4', 'm1', 'n2'];
$index = 0; $result = [];
foreach ($arr1 as $item) {
if (!isset($arr2[$index])) $index = 0;
$result[] = $item.$arr2[$index];
$index++;
}
Answer the question
In order to leave comments, you need to log in
You have pretty good code. You can change it a little, relying on the fact that it is the second array that is shorter than the first:
$result = [];
$limit = count($arr2);
foreach ($arr1 as $index => $item) {
$result[] = $item . $arr2[$index % $limit];
}
$result = array_map(function($item, $i) use ($arr2) {return $item . $arr2[$i % count($arr2)];}, $arr1, array_keys($arr1));
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question