Claude Deslandes
Claude Deslandes

Reputation: 23

If statement check if string is a question mark

I have been programming in PHP since almost 15 years, and today I am asking a simple question that is puzzeling me. I need to check if the string is a "?"... but it does not work.

$niveau = 0;
$result = "Original";
if($niveau == "?") $result = "Found a question";
echo "Result :".$result;

Output: Result : Found a question

Question, since the value of $niveau is 0, the if statement should not change the value of $retour, but it DOES! Why? Can somebody explain this behaviour?

Upvotes: 2

Views: 211

Answers (2)

LF-DevJourney
LF-DevJourney

Reputation: 28564

You should compare the same type variable. When has different type, the result may is not what you're expected.

"0" == "?" // is false
0 == "?"   // is true (PHP 7.3)

When compare a string with int, the string will be take as a int.

intval("?") // which is 0 (PHP 7.3)

so 0 == 0 will return true;

Upvotes: 1

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167250

This is one of Backward Incompatible Changes, which works fine in PHP 8, but not in PHP Version < 8. The problem here is you're comparing string with a number, where it might go wrong.

0 == "foo" // True (PHP < 8) / False (PHP 8)

It is because, the integral value of any string is 0:

<?php
  echo intval("Hello"); // 0
  echo intval("?");     // 0

And comparison with 0 gives true.

So convert $niveau to string and then compare for backward compatibility.

<?php
  $niveau = 0;
  $result = "Original";
  if ($niveau . "" == "?") {
    $result = "Found a question";
  }
  echo "Result :".$result;

This gives me:

Result :Original

Check here on all the versions!

Alternate way, use strict check with three ===:

if ($niveau === "?")

Upvotes: 1

Related Questions