Home  >  Article  >  Backend Development  >  Introduction to the use of php ternary operator, php operator_PHP tutorial

Introduction to the use of php ternary operator, php operator_PHP tutorial

WBOY
WBOYOriginal
2016-07-12 08:58:26786browse

Introduction to the use of php ternary operator, php operator

When we write PHP, if{...}else{...} is probably the most used Yes, but sometimes, we can use the ternary operation in C, which can reduce the code a lot! This article talks about some of my techniques and things to pay attention to when using ternary operations in PHP development. Coders who need it can refer to it.

Today a netizen posted a question in the group. It’s not difficult, but it may be wrong.

<span>echo</span> 
<span>$a</span> == 1 ? 'one' : 
<span>$a</span> == 2 ? 'two' : 
<span>$a</span> == 3 ? 'three' : 
<span>$a</span> == 4 ? 'foura' : 'other'<span>; 
</span><span>echo</span> "\n"; 

The output result is:

82c2f54f4cf245029ffb326befd49b3f

The result is: four

I didn’t understand it at first, but according to my understanding, the logic should be like this:
echo ($a == 1 ? 'one' :
( $a == 2 ? 'two' :
( $a == 3 ? 'three' :
($a == 4 ? 'four' : 'other'))));
The output is: two

Later, under the guidance of kevinG (qq:48474) and referring to the PHP manual, I finally understood that the interpretation of PHP's ternary symbols is from left to right,
130f405214148a14c306f9e82c67496cfalse=>$a==2?true=>'two'=true=>'three'=true=>'four'

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1102860.htmlTechArticlephp Introduction to the use of ternary operator, php operator When we write PHP, maybe if{... }else{...} is the most used, but sometimes, we can use the ternary operation in C, which can make...
Statement:
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