Overview of PHP shorthand
Asked Answered
T

10

36

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;
Thimbleful answered 31/12, 2010 at 0:28 Comment(3)
What do you mean by "shorthand"?Vivyanne
This ain't Perl, there's not a lot of "shorthand" in PHP. Shorter and more concise ways to do certain things? Possibly. Shorthand? Not so much. Your code will mostly become shorter by learning what all the different functions do and finding a nice one that does what you want, or combining a few of them to achieve the desired effect.Pulpiteer
Now in PHP 5.4: print $var ?: 'foo' if you simply want to check if the value is truthy or use a default string of "foo".Reni
G
70

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
<?=$foo?>

//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;
endforeach;

//Another way of If/else:
if ($x > 10):
    doX();
    doY();
    doZ();
else:
    doA();
    doB();
endif;

//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)
   doX();
$x = 1000;

// PHP 5.4 introduced an array shorthand

$a = [1, 2, 3, 4];
$b = ['one' => 1, 'two' => 2, 'three' => 3, 'four' => 4];
Gerta answered 31/12, 2010 at 0:52 Comment(7)
How is that alternative syntax "shorthand"? That's longhand, if anything. I'd go along with <?= though, if it wasn't discouraged and relied on short open tags.Pulpiteer
$x = 'xxxx'; $x && $array['new'] = $x . Whats this means?Biflagellate
$x = 'xxxx'; if($x AND ($array['news'] = $x)) { // nothing }Reni
$x = 'xxxx'; if('xxxx' AND 'xxxx') { // nothing }Reni
Yes - but you're not making the purpose clear, which is to assign $x to $array['new'] only if $x evaluates to true. It's equivalent to: if ($x) $array['new'] = $x;Loquat
@Pulpiteer - in php=>5.4 <?= doesn't rely on short open tags,Forecast
Your shorthand approach on printing does not work anymore in PHP 7.Daube
H
23

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.

Hairline answered 31/12, 2010 at 0:37 Comment(9)
@Felix Would this be compared to the || operator in JavaScript?Vivyanne
@Jacob Relkin: I cannot say if it works the same in every case but in general it has the same effect (to be very exact, || in JS is || in PHP too ;) (it just returns a boolean in PHP and not the value)).Hairline
@Felix Yeah, that's about what I thought. :)Vivyanne
@Jacob: Chaining works (e.g., $foo = false ?: 0 ?: 42), so I think it would work the same as JavaScript's ||. The differences may lie in what PHP considers to be false (e.g., '0').Easternmost
I didn't downvote this, but perhaps because the boolean statement $foo = $bar is not boolean, but an assignment statement instead. Also, after the ? operator, there is no value for the "true" side of the statement, only $baz is returned if your boolean statement is false.Gracielagracile
@Mattygabe: Uhm. You might have misunderstood something. This is the new shorthand syntax for $foo = $bar ? $bar : $baz introduced in PHP 5.3. The statement is correct.Hairline
@Felix Kling, while I believe you that it's new "shorthand" syntax since 5.3, both of your statements are still using the assignment operator (=) rather than the equals (==) or identity (===) operators. Assignment will always return true I believe, and that little (yet important) typo may have been why @downvoter down voted you. But it's just a guess. Edit: As it should, assignment operations return the value assigned, which as long as you're not assigning whatever PHP concludes to be the same as "false", it will return true.Gracielagracile
@Mattygabe: I'm sorry, but there is not typo. As I have written in my answer: it assigns the value of $bar to $foo if $bar evaluates to true (else $baz) . From the documentation: Since PHP 5.3, it is possible to leave out the middle part of the ternary operator. Expression expr1 ?: expr3 returns expr1 if expr1 evaluates to TRUE, and expr3 otherwise. And that is exactly what I'm doing. I don't want to compare $foo and $bar. I want to assign the value of $bar to $foo iff $bar evaluates to true. Maybe it is clearer when I write: $foo = ($bar ?: $baz);Hairline
My mistake, you are correct Felix. The parentheses certainly help as that was what I was missing.Gracielagracile
R
16

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; });
Reliant answered 31/12, 2010 at 0:56 Comment(4)
array_map can also be used to do the same thing as array_walk?Gerta
They are similar. array_map accepts an array by value and returns a new array, while array_walk modifies the array itself.Reliant
+1 to balance out the random downvote. That's some legitimate code. I prefer array_merge($defaults, $thing), but unions are fine too.Pulpiteer
+1 array_merge() and + are different functions for different purposes. I use both at least once in every project.Reni
S
5

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';
}
Selfdefense answered 19/4, 2017 at 13:1 Comment(1)
Introduced in PHP 7, some 5 years after the question was asked. A useful operator indeed. More about ?? and ?: here: #34571830Dinesen
V
3

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.

Vivyanne answered 31/12, 2010 at 0:32 Comment(1)
Also, this operator exists in most C-style languages, not just php.Lampblack
P
2

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

Before:

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

After:

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.

Plod answered 13/9, 2017 at 4:16 Comment(1)
Somewhat related to this example, in the future there will likely be a shorthand anonymous function syntax so the example can be further shortened to something like: usort($list, fn($a, $b) => $a <=> $b); This might look a little confusing but it just means that left of the => is the function signature and right of it is the body which is only a single line and returns the result of that line (despite return not being explicitly written).Plod
G
1

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.

Gracielagracile answered 15/1, 2011 at 3:42 Comment(0)
R
1
<?php
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

Readymade answered 28/5, 2014 at 21:17 Comment(0)
P
1

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.

Plod answered 5/1, 2018 at 4:43 Comment(0)
M
0

PHP 7.4 introduced the arrow functions via the fn keyword.

$x = 5;
$my_function = fn($y) => $x * 5;
echo $my_function(4); // echos "20"

Also see this W3Schools article for a little more explanation.

Monocoque answered 8/9, 2022 at 13:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.