PHP Exercises : Test whether a number is greater than 30, 20 or 10 using ternary operator
PHP : Exercise-21 with Solution
Write a PHP function to test whether a number is greater than 30, 20 or 10 using ternary operator.
Sample Solution: -
PHP Code:
<?php
// Function to test a given number using ternary operators
function trinary_Test($n){
// Ternary operators used to check the value of $n and assign a corresponding message to $r
$r = $n > 30
? "greater than 30"
: ($n > 20
? "greater than 20"
: ($n > 10
? "greater than 10"
: "Input a number at least greater than 10!"));
// Display the result with the input number
echo $n . " : " . $r . "\n";
}
// Test the function with different input values
trinary_Test(32);
trinary_Test(21);
trinary_Test(12);
trinary_Test(4);
?>
Explanation:
- Function Definition:
- The function trinary_Test($n) takes one parameter, $n, which represents the number to be tested.
- Ternary Operators:
- Inside the function, a series of nested ternary operators are used to evaluate the value of $n:
- If $n is greater than 30, it assigns the string "greater than 30" to $r.
- If $n is greater than 20, it assigns "greater than 20".
- If $n is greater than 10, it assigns "greater than 10".
- If none of the above conditions are met, it assigns "Input a number at least greater than 10!".
- Display Result:
- The function uses echo to output the input number and its corresponding message stored in $r, formatted as "<number> : <message>".
- Function Testing:
- The function is called four times with different input values: 32, 21, 12, and 4. Each call tests the number against the defined conditions and outputs the appropriate message.
Output:
32 : greater than 30 21 : greater than 20 12 : greater than 10 4 : Input a number atleast greater than 10!
Flowchart:
PHP Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Write a PHP script to get the last occurred error.
Next: Write a PHP script to get the full URL.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/php-exercises/php-basic-exercise-21.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics