Home >Backend Development >PHP Tutorial >Why Are My Nested Ternary Operators in PHP Returning Unexpected Results?

Why Are My Nested Ternary Operators in PHP Returning Unexpected Results?

Linda Hamilton
Linda HamiltonOriginal
2024-12-28 21:02:18413browse

Why Are My Nested Ternary Operators in PHP Returning Unexpected Results?

Nested Ternary Operators in PHP for Conditional Assignments

You've encountered an issue with your PHP code where you intended to use nested ternary operators but are receiving unexpected results. Let's delve into the problem and provide a solution:

The code you provided:

$province = 7;
$Myprovince = (
($province == 6) ? "city-1" :
($province == 7) ? "city-2" :
($province == 8) ? "city-3" :
($province == 30) ? "city-4" : "out of borders"
);

In this code, you intend to assign different city names based on the value of $province. However, you are getting "city-4" for every value because the ternary operators are not properly nested.

To use nested ternary operators correctly, you need to enclose each ternary operator within parentheses. The correct code should look like this:

$province = 7;
$Myprovince = (($province == 6) ? "city-1" : ((($province == 7) ? "city-2" : ((($province == 8) ? "city-3" : ((($province == 30) ? "city-4" : "out of borders"))))));

By nesting the ternary operators this way, the code will evaluate the conditions in the correct order and assign the appropriate city name based on the value of $province.

The above is the detailed content of Why Are My Nested Ternary Operators in PHP Returning Unexpected Results?. 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