Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the best way to cast a variable to a boolean in php?

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.

like image 644
zzzzBov Avatar asked Feb 04 '11 00:02

zzzzBov


1 Answers

The two ways are:

  1. Explicit cast:

    This is when you explicitly cast the variable using the literal cast operator (bool).

    return (bool) $expression;
    
  2. 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...

like image 198
ircmaxell Avatar answered Oct 05 '22 23:10

ircmaxell