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.
print $var ?: 'foo'
if you simply want to check if the value is truthy or use a default string of "foo". – Reni