duanfan8699 2015-11-11 20:46
浏览 122
已采纳

在PHP三元速记运算符中使用isset()时获取变量的值

In using the shorter ternary operator:

$foo = isset($_GET['bar']) ?: 'hello';

If $_GET['bar'] is set, is it possible for $foo to return the value of $_GET['bar'] instead of true?

Edit: I understand the old school ternary works e.g.,

$foo = isset($_GET['bar']) ? $_GET['bar'] : 'hello';

but I want to use the newschool ternary which is the even shorter version

  • 写回答

5条回答 默认 最新

  • douhao2856 2015-11-11 21:00
    关注

    It sounds like you are asking about the new (as of PHP 7) null coalesce operator. You can do something like:

    $foo = $_GET['bar'] ?? 'hello';
    echo $foo;
    

    Which if $_GET['bar'] is null will set $foo to hello.

    The first operand from left to right that exists and is not NULL. NULL if no values are defined and not NULL. Available as of PHP 7.

    Functional demo: https://3v4l.org/0CfbE

    $foo = $_GET['bar'] ?? 'hello';
    echo $foo . "
    ";
    $_GET['bar'] = 'good bye';
    $foo = $_GET['bar'] ?? 'hello';
    echo $foo;
    

    Output:

    hello
    good bye
    

    Additional reading on it: http://www.lornajane.net/posts/2015/new-in-php-7-null-coalesce-operator

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料