Overview of PHP shorthand

0 votes
asked Dec 31, 2010 by james-simpson

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, so I'd like to learn the different shorthand that exists for the language so that I can read it and start saving time/lines by using it, but I can't seem to find a comprehensive overview of all of the shorthand.

A Google search pretty much exclusively shows the shorthand for if/else statements, but I know there must be more than just that.

By shorthand, I am talking about stuff like:

($var) ? true : false;

8 Answers

0 votes
answered Dec 31, 2010 by jacob-relkin

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.

0 votes
answered Dec 31, 2010 by felix-kling

PHP 5.3 introduced:

$foo = $bar ?: $baz;

which assigns the value of $bar to $foo if $bar evaluates to true (else $baz).

You can also nest the ternary operator (with proper use of parenthesis).

Other than that, there is not much else about it. You might want to read the documentation.

0 votes
answered Dec 31, 2010 by click-upvote

Here are some of the shorthand operators used in PHP.

//If $y > 10, $x will say 'foo', else it'll say 'bar'
$x = ($y > 10) ? 'foo' : 'bar';

//Short way of saying <? print $foo;?>, useful in HTML templates

//Shorthand way of doing the for loop, useful in html templates
for ($x=1; $x < 100; $x++):
   //Do something
end for;

//Shorthand way of the foreach loop
foreach ($array as $key=>$value):
   //Do something;

//Another way of If/else:
if ($x > 10):

//You can also do an if statement without any brackets or colons if you only need to
//execute one statement after your if:

if ($x = 100)
$x = 1000;

// PHP 5.4 introduced an array shorthand

$a = [1, 2, 3, 4];
$b = ['one' => 1, 'two' => 2, 'three' => 3, 'four' => 4];
0 votes
answered Dec 31, 2010 by mfonda

One of my favorite "tricks" in PHP is to use the array union operator when dealing with situations such as functions that take an array of arguments, falling back on default values.

For example, consider the following function that accepts an array as an argument, and needs to know that the keys 'color', 'shape', and 'size' are set. But maybe the user doesn't always know what these will be, so you want to provide them with some defaults.

On a first attempt, one might try something like this:

function get_thing(array $thing)
    if (!isset($thing['color'])) {
        $thing['color'] = 'red';
    if (!isset($thing['shape'])) {
        $thing['shape'] = 'circle';
    if (!isset($thing['size'])) {
        $thing['size'] = 'big';
    echo "Here you go, one {$thing['size']} {$thing['color']} {$thing['shape']}";

However, using the array union operator can be a good "shorthand" to make this cleaner. Consider the following function. It has the exact same behavior as the first, but is more clear:

function get_thing_2(array $thing)
    $defaults = array(
        'color' => 'red',
        'shape' => 'circle',
        'size'  => 'big',
    $thing += $defaults;
    echo "Here you go, one {$thing['size']} {$thing['color']} {$thing['shape']}";

Another fun thing is anonymous functions, (and closures, introduced in PHP 5.3). For example, to multiple every element of an array by two, you could just do the following:

array_walk($array, function($v) { return $v * 2; });
0 votes
answered Dec 15, 2011 by mattygabe

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.

0 votes
answered Dec 28, 2014 by natdrip
class bob {

public function isDebug(){
    return true;

public function debug(){
        echo 'yes dice!!!';

$bob = new bob(); 

($bob->isDebug()) && $bob->debug(); 

Here is another version of shorthand. Hope this helps someone

0 votes
answered Sep 15, 2017 by okonomiyaki3000

Also new in PHP7 is the spaceship operator. Mostly useful in callbacks for things like usort().


usort($list, function ($a, $b) {
    if ($a == $b) return 0;
    return $a < $b;


usort($list, function ($a, $b) { return $a <=> $b; });

Basically, it returns a negative integer, 0, or a positive integer based on the comparison of the left side with the right side.

0 votes
answered Sep 15, 2017 by robert-pounder

Nobody mentioned ??!

// Example usage for: Null Coalesce Operator
$action = $_POST['action'] ?? 'default';

// The above is identical to this if/else statement
if (isset($_POST['action'])) {
    $action = $_POST['action'];
} else {
    $action = 'default';
Welcome to Q&A, where you can ask questions and receive answers from other members of the community.
Website Online Counter