When you step into the door of PHP, learning will never end. Only when the foundation is strong can you flourish and achieve fruitful results. So today I will start the PHP arithmetic series of articles. I hope everyone will practice together regardless of the difficulty. Bar.
The question for the arithmetic exercise in this article is "Write a PHP program to calculate the sum of two given integer values and, if the two values are the same, return three times their sum".
The following is the method I gave:
PHP code:
<?php function test($x, $y) { return $x == $y ? ($x + $y)*3 : $x + $y; } echo test(1, 2)."<br>"; echo test(3, 2)."<br>"; echo test(2, 2)."<br>";
The output calculation result is:
In the above code, the core code part is "$x == $y? ($x $y)*3: $x $y;
", the meaning of this code That is to first determine whether $x and $y are equal. If they are not equal, execute "$x $y". If they are equal, execute "($x $y)*3".
In this example, the first pair of parameters we give are 1 and 2, which are different values, so the returned result is their sum, which is 3;
The second The parameters for the pair are 3 and 2. Similarly, the returned sum is 5;
The parameters given for the third pair are 2 and 2, which are two identical values, so the returned result is three times their sum. times, that is, 3*(2 2)=12.
Here you need to master an important operator, the ternary operator "?:".
The syntax format is "(expr1) ? (expr2) : (expr3)
"
When expr1 is evaluated to TRUE, the value is expr2, and expr1 is evaluated. The value when FALSE is expr3.
Note:
Since PHP 5.3, the middle part of the ternary operator can be omitted. The expression expr1 ?: expr3 returns expr1 if expr1 evaluates to TRUE and expr3 otherwise.
For a detailed introduction to PHP operators, you can read the "PHP Operators" chapter in the manual.
Finally, I would like to recommend to you the latest free course on our platform "Entering the World of PHP from 0"~ Come and learn!
The above is the detailed content of PHP Algorithm Exercise 1: Calculate the sum of two numbers and three times their sum. For more information, please follow other related articles on the PHP Chinese website!