I was reading this question and saw this line:
if ($a == $b) { return true } else { return false }
And it led me to wondering, what is the best way to cast a variable of unknown type (could be string, could be int; who knows? who cares?) to a boolean?
Of course, if ($var) { return true; } else { return false; }
would do the trick, but I think return $var ? true : false;
is probably better.
For that matter:
return $var && true
return $var || false
return !empty($var)
are all probably better, but is there a best way to cast to bool? More importantly, what makes it best?
Edit to clarify:
This wasn't written with the intention of being a comprehensive list of the ways to cast to a boolean. My question is specifically on explicit casting. Before I learned about empty
I used isset($var) && $var
as it would prevent errors from being thrown on undeclared variables. Now i use !empty($var)
as it's faster to type.
!empty
has the (dis)advantage of not throwing any E_NOTICE
errors when the variable isn't defined. This could be considered good if you're checking $_GET
or $_SESSION
variables, for the majority of other variables, I suppose this may be considered bad as it would hide issues where a variable is uninitialized where it should have been initialized.
I was curious as to whether other developers have another way of doing things that I hadn't known about.