Iterating Variables using for loop

Hello all,
Newbie here. Just started learning PHP and Struggling to solve this task.
Task: Iterate a variable from 1 to 10 and print all numbers except 4 and 6 and exit loop at 8.

<?php 
function iterateVariables () {
for ($x = 1; $x <= 10; $x++) {
    echo "The number is: $x <br>";
 }
}
iterateVariables ()
?>
for ($x = 1; $x <= 10; $x++) {
  if ($x === 8) {
    break;
  }
  if ( $x !== 4 || $x !==6) {
     echo "The number is : " . $x . "<br>";
  }
}

Not tested, but should work.

1 Like

Many thanks, @Strider64. Appreciate it.
Instead of OR (||), I used AND (&&) Logical Operator to get the desired output.

function iterateVariables () {
  for ($x = 1; $x <= 10; $x++) {
  if ($x === 8) {
    break;
  }
  if ( $x !== 4 && $x !==6) {
     echo "The number is : " . $x . "<br>";
  }
}
}
iterateVariables ();

Output:
The number is: 1
The number is: 2
The number is : 3
The number is: 5
The number is: 7

More to the point, do you understand what the difference is? If not than you are no better off than you were before.

1 Like

Understood. Thank you for checking up on me. :blush:

Sponsor our Newsletter | Privacy Policy | Terms of Service