Home > Backend Development > PHP Tutorial > Nested example of ternary operator in php

Nested example of ternary operator in php

巴扎黑
Release: 2023-03-14 18:34:01
Original
5645 people have browsed it

// 乍看起来下面的输出是 '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.
Copy after login
/**
 *先判断$_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);
Copy after login

The above is the detailed content of Nested example of ternary operator in php. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template