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条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?