T
T
Tamara Lamova2021-08-01 06:42:36
PHP
Tamara Lamova, 2021-08-01 06:42:36

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];


There is a need to “merge” these two arrays into one,
and when the second one runs out of values, return it to the beginning,
so that it turns out like this:

$result = ['a1',  'b2',  'c3',  'd4',  'e1',  'f2',  'g3',  'h4',  'i1',  'j2',  'k3',  'l4',  'm1',  'n2'];


So far I've done it simple:
$index = 0; $result = [];
foreach ($arr1 as $item) {
    if (!isset($arr2[$index])) $index = 0;
    $result[] = $item.$arr2[$index];
    $index++;
}


But it doesn’t look very good ...

How to make it more concise / more correct?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Sokolov, 2021-08-01
@tom-lam

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];
}

Or shorter, worse, less readable:
hellish one-liner
$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 question

Ask a Question

731 491 924 answers to any question