问题
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...
回答1:
It would be (PHP 5.3+):
echo $post['story'] ?: $post['message'] ?: $post['name'];
And for PHP 7:
echo $post['story'] ?? $post['message'] ?? $post['name'];
回答2:
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.
回答3:
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];
}
回答4:
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
回答5:
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';
回答6:
You can try it
<?php
echo array_shift(array_values(array_filter($post)));
?>
回答7:
That syntax would echo 1 if any of these are set and not false, and 0 if not.
Here's a one line way of doing this which works and which can be extended for any number of options:
echo isset($post['story']) ? $post['story'] : isset($post['message']) ? $post['message'] : $post['name'];
... pretty ugly though. Edit: Mario's is better than mine since it respects your chosen arbitrary order like this does, but unlike this, it doesn't keep getting uglier with each new option you add.
回答8:
Because variety is the spice of life:
echo key(array_intersect(array_flip($post), array('story', 'message', 'name')));
来源:https://stackoverflow.com/questions/8203755/using-short-circuiting-to-get-first-non-null-variable