Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using short circuiting to get first non-null variable

Tags:

What's the equivalent of the following (based in JS style) in PHP:

echo $post['story'] || $post['message'] || $post['name'];

So if story exists then post that; or if message exist post that, etc...

like image 204
MKN Web Solutions Avatar asked Nov 20 '11 18:11

MKN Web Solutions


5 Answers

It would be (PHP 5.3+):

echo $post['story'] ?: $post['message'] ?: $post['name'];

And for PHP 7:

echo $post['story'] ?? $post['message'] ?? $post['name'];
like image 150
Adam Pietrasiak Avatar answered Sep 29 '22 21:09

Adam Pietrasiak


There is a one-liner for that, but it's not exactly shorter:

echo current(array_filter(array($post['story'], $post['message'], $post['name'])));

array_filter would return you all non-null entries from the list of alternatives. And current just gets the first entry from the filtered list.

like image 23
mario Avatar answered Sep 29 '22 22:09

mario


Since both or and || do not return one of their operands that's not possible.

You could write a simple function for it though:

function firstset() {
    $args = func_get_args();
    foreach($args as $arg) {
        if($arg) return $arg;
    }
    return $args[-1];
}
like image 23
ThiefMaster Avatar answered Sep 29 '22 20:09

ThiefMaster


As of PHP 7, you can use the null coalescing operator:

The null coalescing operator (??) has been added as syntactic sugar for the common case of needing to use a ternary in conjunction with isset(). It returns its first operand if it exists and is not NULL; otherwise it returns its second operand.

// Coalescing can be chained: this will return the first
// defined value out of $_GET['user'], $_POST['user'], and
// 'nobody'.
$username = $_GET['user'] ?? $_POST['user'] ?? 'nobody';
like image 25
billyonecan Avatar answered Sep 29 '22 20:09

billyonecan


Building on Adam's answer, you could use the error control operator to help suppress the errors generated when the variables aren't set.

echo @$post['story'] ?: @$post['message'] ?: @$post['name'];

http://php.net/manual/en/language.operators.errorcontrol.php

like image 30
Scott McClung Avatar answered Sep 29 '22 20:09

Scott McClung