Home > Backend Development > PHP Tutorial > Wedding songs, songs suitable for weddings, associative introduction to PHP ternary operator

Wedding songs, songs suitable for weddings, associative introduction to PHP ternary operator

WBOY
Release: 2016-07-29 08:47:40
Original
1119 people have browsed it

Let’s look at a ternary operation formula first:

Copy the code The code is as follows:


$a=1;$b=2;$c=3;$d=4;
echo $a<$b?'xx':$a<$c?'yy':$a<$d?'zz':'oo';
?>


Generally in accordance with other languages ​​(such as C or Java ) rule, the operation logic of the above code is:

Copy the code The code is as follows:


$a<$b => true => 'xx' ==> End


Then finally The result obtained is 'xx', and subsequent operations will be ignored.
What is surprising is that the final result obtained by PHP's calculation of the above code is 'zz'... Oops, what's going on? Are you cheating...
I followed the old rules, so I had to ask Google for advice, and was told that the ternary operation of PHP is left associative...so I suddenly understood.
I added two brackets to the above code:

Copy the code The code is as follows:


$a=1;$b=2;$c=3;$d=4;
echo (($a<$b?'xx': $a<$c)?'yy':$a<$d)?'zz':'oo';
?>


It is clear at a glance, this is the operation logic of php:

Copy Code The code is as follows:


$a<$b => true => 'xx' => true => 'yy' => true => 'zz' => End


This involves two types of conversion processes, namely 'xx' => true and 'xx' => true.
I don't know if this process is painful, it is indeed difficult to understand...
Finally, go back to the above code again and change it into a right combination like C:

Copy the code The code is as follows:


$a=1;$b=2; $c=3;$d=4;
echo $a<$b?'xx':($a<$c?'yy':($a<$d?'zz':'oo'));
// Just change the position of the brackets. You can’t omit brackets in PHP
?>

The above has introduced the combined introduction of wedding songs, songs suitable for weddings, and PHP ternary operators, including wedding songs, songs suitable for weddings, and I hope it will be helpful to friends who are interested in PHP tutorials.

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