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": "";
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.
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.
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.
Value 0 and 1 is equal to false and true in php.
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' : '';
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