2

I have code like this:

<?php  
$kecuali = "6,8,9";
for ($x = 0; $x < 15; $x++) {
  if ($x == $kecuali) {
    continue;
  }
  echo "The number is: $x <br>";
}
?>

and result like this

The number is: 0
The number is: 1
The number is: 2
The number is: 3
The number is: 4
The number is: 5
The number is: 7
The number is: 8
The number is: 9
The number is: 10
The number is: 11
The number is: 12
The number is: 13
The number is: 14

Why are numbers 8 and 9 still in the result, unlike number 6? How can I fix this so that all 3 of the numbers don't appear in the result?

ggorlen
  • 44,755
  • 7
  • 76
  • 106
Leonard
  • 33
  • 5

1 Answers1

0

== should be avoided; it attempts to coerce the types before running the equivalence test. So "6fjsdkjfds" == 6 happens to be true because the leading "6" is cast to a number before the comparison: (int)"6fjsdkjfds" => 6.

Always use === instead.

Now, this change breaks your code further and seems like a step in the wrong direction. But that's because using your set of numbers as an array and performing a lookup with in_array (or array_key_exists if you want O(1) lookup time using keys instead of values...) is the correct way to test membership, not scanning a string or using == or ===.

Instead, try:

<?php

$skip = [6, 8, 9];

for ($i = 0; $i < 15; $i++) {
    if (in_array($i, $skip)) {
        continue;
    }

    echo "The number is: $i<br>";
}

?>

If $skip (or $kecuali) isn't data you have control over, you might need to parse it into an array with:

$skip = array_map("intval", explode(",", $kecuali));

before the above code.

If you have large arrays, consider improving the complexity to O(n+m) instead of O(n*m) with:

<?php

$skip = [6, 8, 9];
$skip = array_flip($skip);

for ($i = 0; $i < 15; $i++) {
    if (array_key_exists($i, $skip)) {
        continue;
    }

    echo "The number is: $i<br>";
}

?>
ggorlen
  • 44,755
  • 7
  • 76
  • 106