How to use Conditional (Ternary) Operator In PHP

This approach uses the ternary operator to determine the smallest of two numbers in a single line of code.

Example: Illustration of Smallest of given two numbers In PHP using Conditional (Ternary) Operator.

PHP




<?php
  
$num1 = 10;
$num2 = 5;
  
$min = $num1 < $num2 ? $num1 : $num2;
  
echo "The smallest number is: $min";
  
?>


Output:

The smallest number is: 5

How to Find the Smallest of given Two Nnumbers In PHP ?

Given two numbers num1 and num2, the task is to find the smallest number between them. Here, we will see the different approaches to solving this problem.

Examples:

Input: 10 5
Ouput: 5

Table of Content

  • Using Conditional (Ternary) Operator
  • Using if-else Statements
  • Using the min Function
  • The sort() Method
  • Using the spaceship operator (<=>)
  • Using min with an Array

Similar Reads

Using Conditional (Ternary) Operator

This approach uses the ternary operator to determine the smallest of two numbers in a single line of code....

Using if-else Statements

...

Using the min Function

This approach uses traditional if-else statements to compare two numbers and assign the smaller one to a variable....

The sort() Method

...

Using the spaceship operator (<=>)

This approach uses the pre inbuilt min function, a built-in PHP function designed for finding the smallest value among multiple inputs....

Using min with an Array

...