skip to Main Content

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

2

Answers


  1. 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;
        }
    ?>
    
    Login or Signup to reply.
  2. You can try this:

    $a = array(1, 2, 3);
    $b = array(3, 2, 5);
    foreach($a as $i => $x){
        echo str_repeat($x, $b[$i]) .'<br>';
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search