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 && truereturn $var || falsereturn !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.
The two ways are:
Explicit cast:
This is when you explicitly cast the variable using the literal cast operator (bool).
return (bool) $expression;
Implicit cast (using operators):
This is where the type is inferred from the expression. In PHP, this includes logical operators and comparison operators, and any function/language construct that expects a boolean such as if and while:
return !!$expression;
or
return $expression == true;
or
return $a == $b;
or
return $a > 1;
or
if ($a)
All methods will fall into one of those two categories.
My suggestion is that if you use any operators (==, !=, >, etc), don't bother casting. But if you're just returning a variable, then cast explicitly...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With