1

I trying to print simple numbers from 1 to 10 using a for loop like this:

for($i = 0; $i <= 10; $i++){
  if($i != 4 || $i != 6){
      echo $i."<br/>";
  }
}

Output:

0
1
2
3
4
5
6
7
8
9
10

I just want the output from 0 to 10 but the output should not contain the numbers 4 and 6.

It is working fine if I use the && operator but does not work if I use||.

I do not understand why this is not working - I think it should work with ||.

2
  • "i think it should work with ||." - Why do you think so? $i != 4 || $i != 6 is always true. It could only be false for an i which is both 4 and 6 at the same time... Commented Mar 14, 2017 at 8:37
  • no, its working with && Commented Mar 14, 2017 at 10:51

3 Answers 3

4

You don't want to print either 4 or 6, so you should be using &&.

The statement if($i != 4 || $i != 6) will trigger whenever $i is not equal to 4, or whenever $i is not equal to 6. Considering 4 is not equal to 6, it will trigger in both cases. It will reach $i = 4, and realise that $i is not equal to 6. This will step into the condition, as you say it only has to hold true for one or the other.

The statement if($i != 4 && $i != 6) implies that $i is not equal to 4 and $i is not equal to 6. Both conditions must hold true at the same time. When $i = 4, $i != 6 will be true, but $i != 4 will be false. Both conditions need to be true, so it will fail. Essentially, this could be rewritten as:

for($i = 0; $i <= 10; $i++){
  if($i != 4) {
    if($i != 6) {
      echo $i."<br/>";
    }
  }
}

To skip over the numbers 4 and 6 in the loop, you have to use the and condition:

for($i = 0; $i <= 10; $i++){
  if($i != 4 && $i != 6){
      echo $i."<br/>";
  }
}

Hope this helps!

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

Comments

1

You want &&. It would not work with ||; that means something different.

"x && y" means "only true if x is true and y is also true; otherwise false."

"x || y" means "true if either x is true or y is true; only false if both are false."

The contrapositive (i.e., "opposite") of ($i != 4 && $i != 6) is ($i == 4 || $i == 6).

Mixing in the || without swapping the comparisons as well means, in your case, "true if $i is not 4, or also true if $i is not 6." Since one of those cases must always true, the result is also always true.

Comments

0
<?php for ($i=0; $i < 10 ; $i++) {
if ($i != 4 && $i !=6){
    echo $i."<br>";}} 
?>

1 Comment

because your condition is select AND operation, not OR operation for more detail, would you like to reading this php.net/manual/en/language.operators.php

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.