r/PHPhelp • u/OdionBuckley • Jan 24 '17
Solved Does negating a non-boolean object have meaning in PHP?
I'm new at PHP, and I've come across a statement that doesn't correspond to anything I recognize from my experience with any other object-oriented language:
if(!$result->fetch_object()){ ... }The fetch_object() method of the MySQLi extension returns an object with string properties, at least according to the manual. It does not return a boolean variable.
What does it mean to negate this non-boolean result and use it as an if-conditional? I've been searching all day, and I can't find anything that explains it. Thank you!
4
u/greg8872 Jan 24 '17
PHP converts between data types automatically which is different from some other languages.
See http://php.net/manual/en/language.operators.comparison.php and http://php.net/manual/en/types.comparisons.php
1
2
2
u/metavulp Jan 25 '17
put simply $result->fetch_object() inside a if() condition will be TRUE if there is any results returned. and will be FALSE if nothing is returned.
"!" inverts the true or false.
so the code you pasted...
if(!$result->fetch_object()){
//do something when nothing is returned... or you finished stepping through all results.
}
6
u/lemminman Jan 24 '17
A NULL value evaluates to false and an object will evaluate to true.