I\'ve been programming in PHP for years now, but I\'ve never learned how to use any shorthand. I come across it from time to time in code and have a hard time reading it, s
This is called the ternary operator, a boolean operator that has three operands:
The first is the boolean expression to evaluate.
The second is the expression to execute if the boolean expression evaluates to TRUE.
The third is the expression to execute if the boolean expression evaluates to FALSE.
Since 5.4 you also have array literals so you no longer need to write:
$myArray = array('some', 'list', 'of', 'stuff');
You can just write:
$myArray = ['some', 'list', 'of', 'stuff'];
Not a huge difference but pretty nice.
So, Jacob Relkin is absolutely right in that the "shorthand" that you mention is indeed called the "ternary" operator, and as Sam Dufel adds, it is very prevalent in other languages. Depending on how the language implements it, it may even be quicker for the server to interpret the logic, as well as let you read it more quickly.
So sometimes what helps when you're learning a new piece of logic or new operators such as this one is to think of the English (or whatever your native language is) to fit around it. Describe it in a sentence. Let's talk through your example:
($var) ? true : false;
What this should read as is this:
Is $var true? If $var is, return the value true. If $var is false, return the value false.
The question mark helps remind you that you're asking a question that determines the output.
A more common use-case for the ternary operator is when you are checking something that isn't necessarily a boolean, but you can use boolean logic to describe it. Take for example the object Car
, that has a property called color
, which is a string-like variable (in PHP). You can't ask if a string is true or false because that makes no sense, but you can ask different questions about it:
$output = $car->color == "blue" ? "Wheee this car is blue!" : "This car isn't blue at all.";
echo $output;
So this line reads as follows:
Is the color of car the same as the string "blue"?
If it is, return the string "Whee this car is blue!", otherwise return the string "This car isn't blue at all."
Whatever the ternary operator returns is being used in the right-hand side of an assignment statement with $output, and that string is then printed.