0

Looking at this single if-statement, if a string is returned, then the condition of the if statement is false? and if null is returned the condition is true? That doesn't seem to make sense, though I know that, that is how this piece of code works. Does null always mean true? and does a stand alone string always get inturpruted as a false condition for an if statement? BTW, this is just somthing ive been racking my head on, doesnt really matter, other than clarity sure would feel good.

 if ($conn->connect_error){
die("Connection failed: " . $conn->connect_error);}
Jin Lee
  • 3,194
  • 12
  • 46
  • 86
  • If a string is returned, the condition is `TRUE` ... unless the string is `"0"`, in which case it's `FALSE`. If it is `NULL`, then the condition will return `FALSE`. See the [**type comparisons documentation**](https://www.php.net/manual/en/types.comparisons.php). – Obsidian Age Jun 19 '19 at 23:40
  • https://www.owasp.org/images/6/6b/PHPMagicTricks-TypeJuggling.pdf – Dharman Jun 19 '19 at 23:43

1 Answers1

3

tl;dr: See the table here, particularly the "Boolean" (far right) column.

A string will only evaluate to false if it contains zero characters (an empty string) or the single character "0" (zero), in which way it behaves like the integer zero. Otherwise, it will always evaluate to true.

Null will always evaluate to false. If it seems to be evaluating as true, there must be something else happening there.

If you want to be sure, you can use the identity operator === and/or its negative compliment !== or your own casting to be sure.

if ($conn->connect_error !== null) {
  // …
}
Garrett Albright
  • 2,844
  • 3
  • 26
  • 45