PHP Program to Find Largest of Three Numbers
if statements like this: compare the first number with the second and third using if and else to print the largest number.Examples
How to Think About It
if conditions. Keep track of the biggest number found so far and finally print it.Algorithm
Code
<?php $a = 5; $b = 9; $c = 3; if ($a >= $b && $a >= $c) { $largest = $a; } elseif ($b >= $a && $b >= $c) { $largest = $b; } else { $largest = $c; } echo "The largest number is $largest"; ?>
Dry Run
Let's trace the input values 5, 9, 3 through the code to find the largest number.
Initialize variables
$a = 5, $b = 9, $c = 3
Check if $a is largest
Is 5 >= 9 and 5 >= 3? No
Check if $b is largest
Is 9 >= 5 and 9 >= 3? Yes
Assign largest
$largest = 9
Print result
Output: The largest number is 9
| Step | Condition | Result |
|---|---|---|
| Check $a | 5 >= 9 and 5 >= 3 | False |
| Check $b | 9 >= 5 and 9 >= 3 | True |
| Assign largest | $largest = 9 | Done |
Why This Works
Step 1: Compare first number
We check if the first number is greater than or equal to both the second and third numbers using &&.
Step 2: Compare second number
If the first number is not largest, we check if the second number is greater than or equal to the other two.
Step 3: Assign largest
If neither first nor second is largest, the third number must be the largest, so we assign it.
Step 4: Print result
Finally, we print the largest number found.
Alternative Approaches
<?php $a = 5; $b = 9; $c = 3; $largest = max($a, $b, $c); echo "The largest number is $largest"; ?>
<?php $a = 5; $b = 9; $c = 3; if ($a > $b) { if ($a > $c) { $largest = $a; } else { $largest = $c; } } else { if ($b > $c) { $largest = $b; } else { $largest = $c; } } echo "The largest number is $largest"; ?>
Complexity: O(1) time, O(1) space
Time Complexity
The program uses a fixed number of comparisons (at most 3), so it runs in constant time O(1).
Space Complexity
Only a few variables are used to store inputs and the largest number, so space complexity is O(1).
Which Approach is Fastest?
Using the built-in max() function is fastest and simplest, but manual comparisons help understand the logic.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Manual if-else | O(1) | O(1) | Learning comparisons and logic |
| max() function | O(1) | O(1) | Quick and clean code |
| Nested if-else | O(1) | O(1) | Clear step-by-step logic |
max() function for a quick and clean solution.