0

I want to run a forloop inside a while loop so that i will be able to change the colors of text accordingly. This is my code

       $leftBrdColorArray = array("g-brd-blue-left", "g-brd-red-left", "g-brd-black-left", "g-brd-yellow-left");
        $rowCount = $runselectGameInfo -> num_rows; //3 is the count
         if($runselectGameInfo -> num_rows > 0){
           while($getGameInfo = $runselectGameInfo -> fetch_assoc()){

             for($i = 0; $i <= $rowCount; $i++){

           Hello <div class="<?php echo $leftBrdColorArray[$i];?>">World</div>
         }
    }
}

But it prints 12 times insted of the rowcount i.e 3.

14
  • Sure! You are looping twice!! Your while and for loops are just the same. Commented Feb 24, 2018 at 17:00
  • probably the while loop runs twice. For each run the for loop runs 3 times. $runselectGameInfo -> fetch_assoc() have 2 results in it. make an echo statement inside the while loop but outside the for loop to test how many times it runs Commented Feb 24, 2018 at 17:01
  • If possible can you illustrate with code. How do i achieve this? Commented Feb 24, 2018 at 17:03
  • for loop runs for the values of $i starting from 0 to 3 inclusive, that is 4 times. Are you sure you get the printing 6 times ? Commented Feb 24, 2018 at 17:03
  • @BRAHMANANDAMOHANTYBRAHMA, did you do the test I suggested ? Commented Feb 24, 2018 at 17:07

1 Answer 1

1

If you want to just print a different color every time but not necessarily all 4 of them (for each row), then the following should do it:

$leftBrdColorArray = array("g-brd-blue-left", "g-brd-red-left", "g-brd-black-left", "g-brd-yellow-left");
$arrsize = count($leftBrdColorArray);
        $rowCount = $runselectGameInfo -> num_rows; //3 is the count
         if($runselectGameInfo -> num_rows > 0){
           i=0;
           while($getGameInfo = $runselectGameInfo -> fetch_assoc()){
             if($i > $arrsize - 1) $i = 0;
             echo 'Hello <div class="$leftBrdColorArray[$i]">World</div>';
             i++;
         }
    }

The problem here will be if you have more rows than colors... you'd have to manage that and add logic to just get a color within the range of your array.

Sign up to request clarification or add additional context in comments.

3 Comments

Yes exactly, that is what i want to achieve, i am trying to get the logic, coz as per you once the loop has more rows than my colors it will be emptied. But i want that to run and colors to be repeated.
I just edited the answer. You have to know the size of the array of colors and the check if has reached the last one, bring it back to zero. I didn't test but this should work.
YES THIS ONE IS WORKING.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.