zzzzBov
zzzzBov

Reputation: 179046

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:

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.

Upvotes: 17

Views: 19973

Answers (5)

Felix Kling
Felix Kling

Reputation: 816442

What I have seen most often in JavaScript: Double negation

return !!$var;

Explanation:

!$var evaluates $var to its opposite boolean value (if $var is no a boolean value, it is converted to boolean first (type conversion)) and the second ! inverts this value again, leading to the boolean value, $var would evaluate too.

Is it the best? That depends on your criteria. As already mentioned, it might be harder to understand (although it is nothing special) but it is definitely the shortest version ;)

It might also depend, which values you consider as true and false. These values evaluate to false by default:

  • the boolean FALSE itself
  • the integer 0 (zero)
  • the float 0.0 (zero)
  • the empty string, and the string "0"
  • an array with zero elements
  • an object with zero member variables (PHP 4 only)
  • the special type NULL (including unset variables)
  • SimpleXML objects created from empty tags

Update:

I think in general one can say, that every code that avoids explicitly returning true or false is better. Be it through explicit casting or implicit type conversion. Of course explicit (by definition) should be easier to understand.

Having code such as return $a ? true : false is redundant. Especially

if ($a == $b) { return true } else { return false }

which could just be written as return ($a == $b).

There must be a reason why this was frowned upon in my undergrads ;).

Update2:

I would avoid expression such as return $var && true. In PHP it would return a boolean, but e.g. in JavaScript or Python, it would return the value of $var if it evaluates to true. And in these languages, this "trick" is used on purpose to achieve certain effects. So for people (more) familiar with these languages, it might not be obvious (without documentation or context) that only a boolean should be returned.

Upvotes: 5

ircmaxell
ircmaxell

Reputation: 165201

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...

Upvotes: 24

Jared Farrish
Jared Farrish

Reputation: 49208

You can cast:

if ((bool)$string)

http://php.net/manual/en/language.types.type-juggling.php

Note, in PHP since 0 == false, you need to use the === comparator to get type comparison, plus value comparison.

http://php.net/manual/en/language.operators.comparison.php

Upvotes: 0

Logan Bailey
Logan Bailey

Reputation: 7127

I personally always use

(bool)$var;

I think this to be the most clear way to cast it to a boolean. Most people coming from another language understand this. One other one you forgot from your is

!!$var;

I find that one a little difficult to read.

Upvotes: 14

zerkms
zerkms

Reputation: 254926

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?

return (bool)$var;

Upvotes: 2

Related Questions