在PHP中与以下代码(基于JS风格)等价的是什么:
echo $post['story'] || $post['message'] || $post['name'];
如果story存在,那么post;或者如果消息存在,张贴,等等
是 (PHP 5.3 +) :
echo $post['story'] ?: $post['message'] ?: $post['name'];
对于PHP 7:
echo $post['story'] ?? $post['message'] ?? $post['name'];
有一行代码,但它并不短:
echo current(array_filter(array($post['story'], $post['message'], $post['name'])));
array_filter
将从备选项列表中返回所有非空项。current
只从过滤列表中获取第一个条目。
由于or
和||
都不返回它们的一个操作数,这是不可能的。
你可以写一个简单的函数:
function firstset() {
$args = func_get_args();
foreach($args as $arg) {
if($arg) return $arg;
}
return $args[-1];
}
从PHP 7开始,您可以使用空合并操作符:
添加了空合并操作符(??)作为语法糖对于需要与。结合使用三元数的常见情况收取()。如果第一个操作数存在且不为NULL,则返回该操作数;否则返回第二个操作数。
// 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';
基于Adam的回答,您可以使用错误控制操作符来帮助抑制未设置变量时产生的错误。
echo @$post['story'] ?: @$post['message'] ?: @$post['name'];
http://php.net/manual/en/language.operators.errorcontrol.php 你可以试试
<?php
echo array_shift(array_values(array_filter($post)));
?>
如果设置了其中任何一个且不为false,该语法将返回1,否则返回0。
这里有一个单行的方法来完成这个工作,并且可以扩展到任意数量的选项:
echo isset($post['story']) ? $post['story'] : isset($post['message']) ? $post['message'] : $post['name'];
…不过很丑。编辑:马里奥的比我的好,因为它尊重你选择的任意顺序,但与此不同的是,它不会随着你添加的每一个新选项而变得越来越难看。
因为变化是生活的调味品:
echo key(array_intersect(array_flip($post), array('story', 'message', 'name')));