php ternary operator formatting

后端 未结 3 1946
一个人的身影
一个人的身影 2021-01-25 23:57

This works:

\"/>

This does n

相关标签:
3条回答
  • 2021-01-26 00:49

    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'] : '')
    
    0 讨论(0)
  • 2021-01-26 00:50

    Put the expression in the parenthesis:

    echo('<input type="text" name="foo" value="'. (isset($_POST['foo']) ? $_POST['foo'] : '') .'"/>');
    
    0 讨论(0)
  • 2021-01-26 00:59

    IMHO, parenthesis (as suggested by zerkms) makes code unreadable.

    Instead, think something like this:

    $value = isset($_POST['foo']) ? $_POST['foo'] : '';
    echo '<input type="text" name="foo" value="'. $value .'"/>';
    
    0 讨论(0)
提交回复
热议问题