0

I have this really basic PHP code I can't figure out. In the example below, why do I get 'MATCH' when $i = 0, and not for the remaining rows …? It seems to be possible to workaround by using === instead of ==, but I can't understand why.

<?php

$text = 'foo bar';

for ($i = 0; $i <= 5; $i++) {
    echo '<p>' . $i . ': ';

    if ($i == $text) {
        echo 'MATCH!';
    } else {
        echo 'NOPE';
    }
}

?>
user1730273
  • 51
  • 1
  • 5

1 Answers1

1

PHP 8 has fixed that part.

Use strcmp with ===

// Use strcmp() function 
if (strcmp($i, $text) === 0) { // check datatype as well
    echo 'MATCH!';
} else {
    echo 'NOPE';
}
Ravi Hirani
  • 6,511
  • 1
  • 27
  • 42