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.

How to Find Largest Number using Ternary Operator in PHP?

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.

Table of Content

  • Comparing Two Numbers
  • Comparing Three Numbers

Similar Reads

Approach 1: Comparing Two Numbers

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

Approach 2: Comparing Three Numbers

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

Contact Us