phparrayselementkey-value

How to get an array element value repeated based on another array element


I am trying to get a value repeated number of times the value of an array element I have the following arrays

<?php
$a = array(1, 2, 3);
$b = array(3, 2, 5);
foreach ($b as $x) {
    for ($i = 1; $i <= $x; $i++) {
        echo print_r($i).'<br>';
    }
}

Output:

11
21
31
11
21
11
21
31
41
51

I expect the output to be:-

1112233333

Solution

  • Here you go -

    <?php
        $a = array(1,2,3);
        $b = array(3,2,5);
        $index = 0;
        foreach($b as $x) {
            for($j = 1;$j <= $x; ++$j) {
                echo $a[$index];
            }
            ++$index;
        }
    ?>