skip to Main Content

My teacher asked me to Create a PHP script that prints numbers from 1 to 50 using a for loop. However, when the
loop encounters a multiple of 5, it should skip that number using the continue statement and
continue to the next iteration.

I created

But not Working it. Please help me.

for ($i =1; $i<=50; $i++) {  
     
     if ($i * 5) {
        continue;
     }
        echo $i . "n";  
       
} 

3

Answers


  1. for ($i = 1; $i <= 50; $i++) {
        if ($i % 5 == 0) {
            continue;
        }
        echo $i . "n";
    }
    
    Login or Signup to reply.
  2. Check out the modulo operator. "%". That should make it easy to do what you need.

    Login or Signup to reply.
  3. Use the modulo operator (%) to get the remainder of dividing the loop counter value by the desired break point value.

    When the remainder is 0, you know that it has reached the break point value (because, for example the remainder from 5 / 5 is 0, and so is the remainder from 10 / 5, etc etc).

    Example:

    for ($i = 1; $i <= 50; $i++) {
        if ($i % 5 == 0) {
            continue;
        }
        echo $i . "n";
    }
    

    Runnable demo: https://3v4l.org/pJVXi

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search