PHP Program - Find Largest Number among three Numbers
Three numbers x, y and z are given and the largest number among these three numbers can be found out using below methods.
Method 1: Using If statement
In the example below, only if conditional statements are used.
<?php function largest($x, $y, $z) { $max = $x; if ($x >= $y && $x >= $z) $max = $x; if ($y >= $x && $y >= $z) $max = $y; if ($z >= $x && $z >= $y) $max = $z; echo "Largest number among $x, $y and $z is: $max\n"; } largest(100, 50, 25); largest(50, 50, 25); ?>
The above code will give the following output:
Largest number among 100 , 50 and 25 is: 100 Largest number among 50 , 50 and 25 is: 50
Method 2: Using If-else statement
It can also be solved using If-else conditional statements.
<?php function largest($x, $y, $z) { $max = $x; if ($x >= $y && $x >= $z) $max = $x; elseif ($y >= $x && $y >= $z) $max = $y; else $max = $z; echo "Largest number among $x, $y and $z is: $max\n"; } largest(100, 50, 25); largest(50, 50, 25); ?>
The above code will give the following output:
Largest number among 100 , 50 and 25 is: 100 Largest number among 50 , 50 and 25 is: 50
Method 3: Using Nested If-else statement
The above problem can also be solved using nested if-else conditional statements.
<?php function largest($x, $y, $z) { $max = $x; if ($x >= $y) { if($x >= $z) $max = $x; else $max = $z; } else { if($y >= $z) $max = $y; else $max = $z; } echo "Largest number among $x, $y and $z is: $max\n"; } largest(100, 50, 25); largest(50, 50, 25); ?>
The above code will give the following output:
Largest number among 100 , 50 and 25 is: 100 Largest number among 50 , 50 and 25 is: 50
Method 4: Using ternary operator
The ternary operator can also be used here.
<?php function largest($x, $y, $z) { $max = $x; $max = ($x > $y)? (($x > $z)? $x : $z) : (($y > $z)? $y : $z); echo "Largest number among $x, $y and $z is: $max\n"; } largest(100, 50, 25); largest(50, 50, 25); ?>
The above code will give the following output:
Largest number among 100 , 50 and 25 is: 100 Largest number among 50 , 50 and 25 is: 50
Recommended Pages
- PHP Program - To Check Prime Number
- PHP Program - Bubble Sort
- PHP Program - Selection Sort
- PHP Program - Maximum Subarray Sum
- PHP Program - Reverse digits of a given Integer
- PHP - Swap two numbers
- PHP Program - Fibonacci Sequence
- PHP Program - Insertion Sort
- PHP Program - Find Factorial of a Number
- PHP Program - Find HCF of Two Numbers
- PHP Program - Merge Sort
- PHP Program - Shell Sort
- Stack in PHP
- Queue in PHP
- PHP Program - Find LCM of Two Numbers
- PHP Program - To Check Whether a Number is Palindrome or Not
- PHP Program - To Check Whether a String is Palindrome or Not
- PHP Program - Heap Sort
- PHP Program - Quick Sort
- PHP - Swap Two Numbers without using Temporary Variable