使用短路来获取第一个非空变量
在 PHP 中,以下内容(基于 JS 风格)的等价物是什么:
echo $post['story'] || $post['message'] || $post['name'];
所以如果故事存在,那么发布它;或者如果消息存在,等等......
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...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
它将是(PHP 5.3+):
对于PHP 7:
It would be (PHP 5.3+):
And for PHP 7:
有一个单行代码,但它并不短:
array_filter
会返回替代列表中的所有非空条目。current
只是从过滤列表中获取第一个条目。There is a one-liner for that, but it's not exactly shorter:
array_filter
would return you all non-null entries from the list of alternatives. Andcurrent
just gets the first entry from the filtered list.由于
or
和||
都不返回其操作数之一,这是不可能的。不过,您可以为其编写一个简单的函数:
Since both
or
and||
do not return one of their operands that's not possible.You could write a simple function for it though:
从 PHP 7 开始,您可以使用 空合并运算符:
As of PHP 7, you can use the null coalescing operator:
基于 Adam 的答案,您可以使用错误控制运算符来帮助抑制未设置变量时生成的错误。
http://php.net/manual/en/language.operators.errorcontrol.php
Building on Adam's answer, you could use the error control operator to help suppress the errors generated when the variables aren't set.
http://php.net/manual/en/language.operators.errorcontrol.php
你可以尝试一下
You can try it
如果其中任何一个已设置且不为 false,则该语法将回显 1,否则回显 0。
这是一种执行此操作的单行方法,该方法有效并且可以扩展为任意数量的选项:
...虽然相当丑陋。编辑:马里奥的比我的更好,因为它像这样尊重您选择的任意顺序,但与此不同的是,它不会随着您添加的每个新选项而变得越来越难看。
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:
... 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.
因为多样性是生活的调味品:
Because variety is the spice of life: