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": "";
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
First off,
trueis 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 == truecomparison inside theif. It’s exactly the same asif ($var) {(For a double==comparison. An identical comparison===would need to be explicit).Third, I prefer the pre-initialization. So:
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: