search
HomeBackend DevelopmentPHP TutorialAbout a problem encountered by PHP conditional operator and its solution

About a problem encountered by PHP conditional operator and its solution

Jul 14, 2018 pm 01:54 PM
phprear endBackend DevelopmentServer developmentprogrammer

This article mainly introduces a problem and solution encountered about PHP conditional operators. It has a certain reference value. Now I share it with you. Friends in need can refer to it.

Encountered today Come to a question about the nested use of conditional operators (ternary expressions) in PHP

Phenomena

Let’s first look at a piece of C language code (test.c):

#include<stdio.h>
int main() {
  int x = 1;
  int shit = x == 1 ? 100 : 
     x == 2 ? 200 : 300;
  printf("shit的值:%d\n", shit);
  return 0;
}</stdio.h>

Compile and run it

root$ gcc test.c -o test && ./test
shit的值:100

The answer is as expected, because x==1, so 100 is assigned to shit.

But if we rewrite the above code in PHP (test.php):

<?php $x = 1;
$shit = $x == 1 ? 100 : 
   $x == 2 ? 200 : 300;
echo "shit的值:$shit\n";

Execute it:

root$ php test.php
shit的值:200

We find that it returns The results are different, why is this?

Troubleshooting

First of all, we suspect that it may be a priority issue with comparison operator(==) and conditional operator(?:) in PHP , let’s check the PHP official documentation

##== has a higher priority than ?: (C language This is also true), so

$shit = $x == 1 ? 100 : 
   $x == 2 ? 200 : 300;
is equivalent to

$shit = ($x == 1) ? 100 : 
   ($x == 2) ? 200 : 300;
and it is true when executed once. The possibility of operator priority causing the problem can be ruled out.

But in the official document, there is such a sentence in the example of

operator combination direction:

This is very similar to the phenomenon described above, The problem should be here. After some research, I got the following conclusion:About a problem encountered by PHP conditional operator and its solution

Conclusion

  • The combination direction of the conditional operator (?:) in C language is

    from right to left, each evaluation starts from the rightmost subexpression, so

int x = 1;

int shit = x == 1 ? 100 : 
     x == 2 ? 200 : 300;
//等效于
int shit = x == 1 ? 100 : 
     (x == 2 ? 200 : 300);
//等效于
int shit = x == 1 ? 100 : 
     (300);// 100
  • combination of PHP’s conditional operator (?:) The direction is

    from left to right, and each evaluation starts from the leftmost subexpression, so

$x = 1;
$shit = $x == 1 ? 100 : 
   $x == 2 ? 200 : 300;
//等效于
$shit = ($x == 1 ? 100 : 
   $x == 2) ? 200 : 300;
//等效于
$shit = (100) ? 200 : 300;// 200

is between PHP Conditional operator combination direction, we cannot achieve the effect of if-elseif-elseif-else expression by nesting conditional operators like C/C, unless we add parentheses to the later sub-expressions , in this example it can be solved in this way:

$shit = $x == 1 ? 100 : 
   ($x == 2 ? 200 : 300);
However, when there are many conditional branches, code readability problems (stacked brackets) will occur:

$shit = $x == 1 ? 100 :
     ($x == 2 ? 200 :
     ($x== 3 ? 300 :
     ...
     ($x == 8 ? 800 : 900)))))));
Due to PHP's writing method of not stacking parentheses is inconsistent with C/C in terms of execution results, and the default combination direction can only be changed by adding parentheses to achieve the expected results, so the PHP document simply does not recommend the use of nested conditional operators:

Note:
It is recommended that you avoid "stacking" ternary expressions. PHP's
behaviour when using more than one ternary operator within a single statement is non-obvious
The above is The entire content of this article is hoped to be helpful to everyone's study. For more related content, please pay attention to the PHP Chinese website!

Related recommendations:

Let’s talk about dependency injection, containers and appearance patterns in framework development (Part 2)

How to solve the problems of PHP Problems with concurrency and large traffic

The above is the detailed content of About a problem encountered by PHP conditional operator and its solution. For more information, please follow other related articles on the PHP Chinese website!

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
What is the full form of PHP?What is the full form of PHP?Apr 28, 2025 pm 04:58 PM

The article discusses PHP, detailing its full form, main uses in web development, comparison with Python and Java, and its ease of learning for beginners.

How does PHP handle form data?How does PHP handle form data?Apr 28, 2025 pm 04:57 PM

PHP handles form data using $\_POST and $\_GET superglobals, with security ensured through validation, sanitization, and secure database interactions.

What is the difference between PHP and ASP.NET?What is the difference between PHP and ASP.NET?Apr 28, 2025 pm 04:56 PM

The article compares PHP and ASP.NET, focusing on their suitability for large-scale web applications, performance differences, and security features. Both are viable for large projects, but PHP is open-source and platform-independent, while ASP.NET,

Is PHP a case-sensitive language?Is PHP a case-sensitive language?Apr 28, 2025 pm 04:55 PM

PHP's case sensitivity varies: functions are insensitive, while variables and classes are sensitive. Best practices include consistent naming and using case-insensitive functions for comparisons.

How do you redirect a page in PHP?How do you redirect a page in PHP?Apr 28, 2025 pm 04:54 PM

The article discusses various methods for page redirection in PHP, focusing on the header() function and addressing common issues like "headers already sent" errors.

Explain type hinting in PHPExplain type hinting in PHPApr 28, 2025 pm 04:52 PM

Article discusses type hinting in PHP, a feature for specifying expected data types in functions. Main issue is improving code quality and readability through type enforcement.

What is PDO in PHP?What is PDO in PHP?Apr 28, 2025 pm 04:51 PM

The article discusses PHP Data Objects (PDO), an extension for database access in PHP. It highlights PDO's role in enhancing security through prepared statements and its benefits over MySQLi, including database abstraction and better error handling.

How to create API in PHP?How to create API in PHP?Apr 28, 2025 pm 04:50 PM

Article discusses creating and securing PHP APIs, detailing steps from endpoint definition to performance optimization using frameworks like Laravel and best security practices.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!