Thijs
Thijs

Reputation: 61

Combination of array items with loops

I'm struggling with some loop in loop handling. I want to output one incremental item of the $additional array after each 3 items of the $items array. Also, when we arrive at item-15 in the $items array, I want to start from extra-1 again with $additional array.


$items = array(
    "item-1",
    "item-2",
    "item-3",

    "item-4",
    "item-5",
    "item-6",

    "item-7",
    "item-8",
    "item-9",

    "item-10",
    "item-11",
    "item-12",

    "item-13",
    "item-14",
    "item-15",
);

$additional = array(
    "extra-1",
    "extra-2",
    "extra-3",
    "extra-4",
);

In the end I want to end up with something like this:

    "item-1",
    "item-2",
    "item-3",
"extra-1",
    "item-4",
    "item-5",
    "item-6",
"extra-2",
    "item-7",
    "item-8",
    "item-9",
"extra-3",
    "item-10",
    "item-11",
    "item-12",
"extra-4",
    "item-13",
    "item-14",
    "item-15",
"extra-1"

I tried some stuff with different loops (for, foreach and while) in combination with different counters.

Any help is appreciated!

Upvotes: 0

Views: 76

Answers (1)

Ihor Burlachenko
Ihor Burlachenko

Reputation: 4905

The following code does the job:

$length = count($items);
$additionalLength = count($additional);
for ($i = 1; $i <= $length; ++$i) {
    echo $items[$i - 1] . "\n";
    if ($i % 3 === 0) {
        echo $additional[(($i / 3) - 1) % $additionalLength] . "\n";
    }
}

Upvotes: 1

Related Questions