Home  >  Article  >  Backend Development  >  PHP uses the ternary operator to test whether a number is greater than a specified number [with examples]

PHP uses the ternary operator to test whether a number is greater than a specified number [with examples]

藏色散人
藏色散人Original
2021-08-05 14:23:162482browse

The topic of this article is about the use of the ternary operator as stated in the title. I wonder how much you know about the ternary operator? But I believe that after reading this article, everyone will have a preliminary understanding of the ternary operator!

First of all, let me briefly introduce the ternary operator. In fact, the function of the ternary operator "?:" is the same as the "if...else" statement. The if statement is used when the specified condition is true. When executing the code; it doesn’t matter if you don’t understand it yet, let’s explain it with specific examples:

For example, there is such a question: “How do you write a PHP function to use the ternary operator to test whether a number is greater than 30 , 20 or 10”?

I will give my method directly below:

The PHP code is as follows:

<?php

function trinary_Test($n){
    $r = $n > 30
        ? "大于30"
        : ($n > 20
            ? "大于20"
            : ($n >10
                ? "大于10"
                : "输入一个至少大于10的数字!"));
    echo $n." : ".$r."<br>";
}
trinary_Test(32);
trinary_Test(21);
trinary_Test(12);
trinary_Test(4);

The output result is as follows:

PHP uses the ternary operator to test whether a number is greater than a specified number [with examples]

Now I will introduce to you the syntax of the ternary operator:

(expr1)?(expr2):(expr3); //表达式1?表达式2:表达式3

means that if the condition "expr1" is true, execute the statement "expr2", otherwise execute "expr3". (Proper use of the ternary operator can make the code more concise and efficient)

Then understand this syntax and look at the above examples, I believe everyone will understand it at a glance.

In the above code, the variables we give are 32, 21, 12, 4 respectively, and the specified number is 30, 20 or 10; if the variable is greater than the specified number, the expression after the question mark will be executed. ; Otherwise, the expression after the colon will be executed.

Note: This method can also be implemented directly using the if else if statement. Try it locally~

Finally, I would like to recommend the latest and most comprehensive " PHP Video Tutorial》~Come and learn!

The above is the detailed content of PHP uses the ternary operator to test whether a number is greater than a specified number [with examples]. 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