dongwubao4785 2011-07-29 23:58
浏览 33
已采纳

php三元运算符格式化

This works:

<input type="text" name="foo" value="<?php echo isset($_POST['foo']) ? $_POST['foo'] : '' ?>"/>

This does not:

echo('<input type="text" name="foo" value="'.isset($_POST['foo']) ? $_POST['foo'] : ''.'"/>');

Notice: Undefined index: foo in /srv/www/form.php on line 15

Thanks for any help.

  • 写回答

3条回答 默认 最新

  • dongsonglian7303 2011-07-30 00:48
    关注

    PHP's operator precedence rules make it evaluate your second example as follows:

    echo(
      ('<input type="text" name="foo" value="'.isset($_POST['foo']))
        ? $_POST['foo']
        : (''.'"/>')
    );
    

    That doesn't make a lot of sense in several ways. And since the result of isset() is essentially disregarded, this always ends up just trying to print $_POST['foo']. And that results in a notice when it's not set, of course.

    Add parentheses around the actual ternary expression. I.e.

    (isset($_POST['foo']) ? $_POST['foo'] : '')
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

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