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
Check out the modulo operator. "%". That should make it easy to do what you need.
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 from5 / 5
is0
, and so is the remainder from10 / 5
, etc etc).Example:
Runnable demo: https://3v4l.org/pJVXi