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.
将表达式放在括号中:
echo('<input type="text" name="foo" value="'. (isset($_POST['foo']) ? $_POST['foo'] : '') .'"/>');
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. Ie
(isset($_POST['foo']) ? $_POST['foo'] : '')
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 .'"/>';
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.