使用短路来获得第一个非空变量

MKN*_*ons 25 php short-circuiting

在PHP中,以下内容(基于JS样式)相当于:

echo $post['story'] || $post['message'] || $post['name'];
Run Code Online (Sandbox Code Playgroud)

所以,如果故事存在,那么发布; 或者如果消息存在,等等......

pie*_*e6k 38

它将是(PHP 5.3+):

echo $post['story'] ?: $post['message'] ?: $post['name'];
Run Code Online (Sandbox Code Playgroud)

而对于PHP 7:

echo $post['story'] ?? $post['message'] ?? $post['name'];
Run Code Online (Sandbox Code Playgroud)

  • Bingo,这是从5.3开始的正确方法 (3认同)
  • 这将为未设置的变量生成警告 (2认同)

mar*_*rio 16

有一个单行,但它并不完全短:

echo current(array_filter(array($post['story'], $post['message'], $post['name'])));
Run Code Online (Sandbox Code Playgroud)

array_filter会从备选列表中返回所有非空条目.然后current从过滤后的列表中获取第一个条目.


Thi*_*ter 6

由于两个or||不返回它们的操作数这是不可能的一个.

你可以为它编写一个简单的函数:

function firstset() {
    $args = func_get_args();
    foreach($args as $arg) {
        if($arg) return $arg;
    }
    return $args[-1];
}
Run Code Online (Sandbox Code Playgroud)


bil*_*can 5

从 PHP 7 开始,您可以使用空合并运算符

空合并运算符 (??) 已被添加为语法糖,用于需要将三元与 isset() 结合使用的常见情况。如果存在且不为 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';
Run Code Online (Sandbox Code Playgroud)


小智 5

在亚当的答案的基础上,您可以使用错误控制运算符来帮助抑制未设置变量时生成的错误。

echo @$post['story'] ?: @$post['message'] ?: @$post['name'];
Run Code Online (Sandbox Code Playgroud)

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