一起源码网

标题: php中三元运算符的嵌套实例 [打印本页]

作者: 云文章    时间: 2020-4-3 16:30
标题: php中三元运算符的嵌套实例
// 乍看起来下面的输出是 'true'
echo (true?'true':false?'t':'f');

// 然而,上面语句的实际输出是't',因为三元运算符是从左往右计算的

// 下面是与上面等价的语句,但更清晰
echo ((true ? 'true' : 'false') ? 't' : 'f');

// here, you can see that the first expression is evaluated to 'true', which
// in turn evaluates to (bool)true, thus returning the true branch of the
// second ternary expression.
/**
 *先判断$_GET['a']若成立则判断(isset($_GET['b']) ? $_GET['b'] : 'other'),因为有括号,所以
 *会当成一个整体运算
 */
$rs = isset($_GET['a']) ? $_GET['a'] : (isset($_GET['b']) ? $_GET['b'] : 'other');
var_dump($rs);


/**
 * 注意:自左向右结合运算
 *先判断$_GET['a']若成立则 则变成 $_GET['a'] ? $_GET['b'] : 'other';
 *不可忽视括号的作用
 */
$rs = isset($_GET['a']) ? $_GET['a'] : isset($_GET['b']) ? $_GET['b'] : 'other';
var_dump($rs);


作者: 这样挺好    时间: 2022-9-17 18:19
免费提供源代码的网址




欢迎光临 一起源码网 (https://www.171739.xyz/) Powered by Discuz! X3.3