Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

php - Ternary operator with multiple conditions

Hello I am trying to properly format ternary operator to be using multiple conditions in php:

$result = ($var !== 1 || $var !== 2) ? '' : 'default';

The problem is that in this format I always get not true even iv the $var is 1 or 2. With one condition for example $var == 0 it is working fine. Any help will be welcome.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This statement will always be true:

($var !== 1 || $var !== 2)

Because $var can never simultaneously be both values, it will always not be at least one of the two values. Which satisfies the || operator.

If you want to know whether $var is one of the two values:

($var === 1 || $var === 2)

If you want to know if $var is neither of the two values, you can negate the condition:

(!($var === 1 || $var === 2))

Or individually negate the operators in the condition and use && instead of || (since all conditions need to be met to prove the negative, instead of just one condition to prove the positive):

($var !== 1 && $var !== 2)

Depending on readability and personal preference.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...