Home >Backend Development >PHP Problem >How to determine which of two numbers is closest to the value 100 in PHP
In the previous article "How to add "if" to the front of a given string through PHP", I will introduce how to add "if" to the front of a given string through PHP. It is also a study of conditional statements. Today, this article will introduce to you how to determine whether a certain number among two numbers is closest to the value 100. Of course, you can also decide this close value according to the situation.
The specific question is as follows:
How to write a PHP program to check which number among two given integers is closest to the value 100 and return if the two numbers are equal 0.
Now that the conditions and requirements are all in place, let’s start coding!
The following is the implementation method I gave for your reference and study:
<?php function test($x, $y) { $n = 100; $val = abs($x - $n); $val2 = abs($y - $n); return $val == $val2 ? 0 : ($val < $val2 ? $x : $y); } echo test(78, 95)."<br>"; echo test(95, 95)."<br>"; echo test(99, 70)."<br>";
The output result is:
95 0 99
Let’s take a look, the first pair of parameters is (78, 95), the one close to 100 is obviously 95; the second pair of parameters is (95, 95), the same two numbers return 0; the third pair of parameters is (99, 70), returns 99.
Here I will introduce you to a functionabs
. The abs() function in PHP is used to return the absolute value of a number. Its syntax is "abs(number);
", that is to say, the return value is the absolute value of the returned number. If the type of the number number is a floating point type, the returned type is also a floating point type, otherwise it will be returned in the form of an integer.
Then about the ternary operator ?:
(if the expression before the question mark is true, the expression before the colon is executed, otherwise the expression after the colon is executed), I won’t introduce much. , has been used and introduced many times in previous articles.
Finally, I would like to recommend to you the latest and most comprehensive "PHP Video Tutorial"~ Come and learn!
The above is the detailed content of How to determine which of two numbers is closest to the value 100 in PHP. For more information, please follow other related articles on the PHP Chinese website!