PHP Exercises: Compute the sum of three given integers. If the two values are same return the third value
54. Sum of Three with Duplicate Override
Write a PHP program to compute the sum of three given integers. If the two values are same return the third value.
Sample Solution:
PHP Code :
<?php
// Define a function named 'test' that takes three parameters and returns a value based on certain conditions
function test($x, $y, $z)
{
// Check if all three parameters are equal; if true, return 0
if ($x == $y && $y == $z) return 0;
// Check if $x is equal to $y; if true, return $z
if ($x == $y) return $z;
// Check if $x is equal to $z; if true, return $y
if ($x == $z) return $y;
// Check if $y is equal to $z; if true, return $x
if ($y == $z) return $x;
// If none of the above conditions are met, return the sum of $x, $y, and $z
return $x + $y + $z;
}
// Test the 'test' function with different input values and display the results
echo (test(4, 5, 7))."\n";
echo (test(7, 4, 12))."\n";
echo (test(10, 10, 12))."\n";
echo (test(12, 12, 18))."\n";
?>
Explanation:
- Function Definition:
- The test function takes three parameters: $x, $y, and $z. Based on various conditions, it returns a specific value.
- Conditions:
- All Equal: If all three parameters ($x, $y, and $z) are equal, the function returns 0.
- Two Equal (Returning Third):
- If $x and $y are equal, it returns $z.
- If $x and $z are equal, it returns $y.
- If $y and $z are equal, it returns $x.
- None of the Above: If none of the values are equal, it returns the sum of $x, $y, and $z.
Output:
16 23 12 18
Flowchart:

For more Practice: Solve these Related Problems:
- Write a PHP script to compute the sum of three integers but if any two are equal, return the remaining third number.
- Write a PHP function to sum three numbers and check for equality among any two, outputting only the unique value if duplicates occur.
- Write a PHP program to add three integers and conditionally exclude the duplicate values from contributing to the sum.
- Write a PHP script to design logic that compares three integers and if a pair is found identical, returns the value of the odd one out.
Go to:
PREV : Sum with Digit-Length Constraint.
NEXT : Sum Excluding 13 and Right Side.
PHP Code Editor:
Contribute your code and comments through Disqus.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.