Open In App

How to Find Largest Number using Ternary Operator in PHP?

Last Updated : 24 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Given three different numbers, the task is to find the Largest Number using Ternary Operator in PHP. In PHP, the ternary operator (?:) allows you to make a quick decision based on a condition. It is a shorthand method to write an if…else statement. You can use the ternary operator to find the largest number among two or more numbers.

Approach 1: Comparing Two Numbers

The simplest use case of the ternary operator is to compare two numbers and return the largest one.

PHP
<?php

$num1 = 10;
$num2 = 20;

$largest = ($num1 > $num2) ? $num1 : $num2;

echo "Largest Number: $largest";

?>

Output
Largest Number: 20

In this example, if $num1 is greater than $num2, then $num1 is assigned to $largest; otherwise, $num2 is assigned.

Approach 2: Comparing Three Numbers

You can also use the ternary operator to compare three numbers and find the largest one.

PHP
<?php

$num1 = 10;
$num2 = 20;
$num3 = 15;

$largest = ($num1 > $num2) 
    ? ($num1 > $num3 ? $num1 : $num3) 
    : ($num2 > $num3 ? $num2 : $num3);

echo "Largest Number: $largest";

?>

Output
Largest Number: 20

In this example, the outer ternary operator compares $num1 and $num2 first. If $num1 is greater, it compares $num1 with $num3 to determine the largest. If $num2 is greater, it compares $num2 with $num3 to determine the largest.


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads