Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should boolean expressions be written in PHP?

How should the following boolean expression be written in PHP:

$foo = "";
if($var==TRUE){
    $foo = "bar";
}

or

if($var==TRUE){
    $foo = "bar";
}else{
    $foo = "";
}

or

$foo = ($var==TRUE) ? "bar": "";
like image 846
Stann0rz Avatar asked Aug 18 '10 16:08

Stann0rz


People also ask

What is Boolean expression in PHP?

Definition and Usage This is one of the scalar data types in PHP. A boolean data can be either TRUE or FALSE. These are predefined constants in PHP. The variable becomes a boolean variable when either TRUE or FALSE is assigned.

What does ?: Mean in PHP?

The Scope Resolution Operator (also called Paamayim Nekudotayim) or in simpler terms, the double colon, is a token that allows access to static, constant, and overridden properties or methods of a class.

How initialize boolean in PHP?

To explicitly convert a value to bool, use the (bool) or (boolean) casts. However, in most cases the cast is unnecessary, since a value will be automatically converted if an operator, function or control structure requires a bool argument.

Is 1 false or true PHP?

Value 0 and 1 is equal to false and true in php.


1 Answers

First off, true is not a constant, it's a token, so please don't uppercase it (I know some standards do that, but I think it confuses the meaning)...

Second, you don't need the redundant $var == true comparison inside the if. It's exactly the same as if ($var) { (For a double == comparison. An identical comparison === would need to be explicit).

Third, I prefer the pre-initialization. So:

$foo = '';
if ($var) {
    $foo = 'one status';
} else {
    $foo = 'another status';
}

If you don't need the else branch, just remove it. I prefer the pre-initialization since it forces you to initialize the variable, and it prevents cases where you forget to initialize it in one of the branches. Plus, it gives you a type hint when you go back to read the function later...

And for a simple branch like that, using the ternary syntax is fine. If there's more complex logic, I'd stay away though:

$foo = $var ? 'bar' : '';
like image 118
ircmaxell Avatar answered Oct 13 '22 23:10

ircmaxell