PHP Exercises: Compute the sum of the two given integer values
PHP Basic Algorithm: Exercise-1 with Solution
Write a PHP program to compute the sum of the two given integer values. If the two values are the same, then returns triple their sum.
Sample Solution:
PHP Code :
<?php
// Define a function named "test" that takes two parameters, $x and $y
function test($x, $y)
{
// Use the ternary operator to check if $x is equal to $y
// If true, return the result of multiplying the sum of $x and $y by 3
// If false, return the sum of $x and $y
return $x == $y ? ($x + $y)*3 : $x + $y;
}
// Call the test function with arguments 1 and 2, and echo the result
echo test(1, 2) . "\n";
// Call the test function with arguments 3 and 2, and echo the result
echo test(3, 2) . "\n";
// Call the test function with arguments 2 and 2, and echo the result
echo test(2, 2) . "\n";
?>
Sample Output:
3 5 12
Visual Presentation:
Flowchart:
PHP Code Editor:
Contribute your code and comments through Disqus.
Previous: PHP Basic Algorithm Exercises Home
Next: Write a PHP program to get the absolute difference between n and 51. If n is greater than 51 return triple the absolute difference.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics