PHP Program to check whether the number is odd or even using ternary operator

What is a ternary operator?

A ternary operator can be defined as a conditional operator that accomplishes both comparisons and conditions in a single line of code. This can be considered an alternative method of implementing if-else or nested if-else statements. This conditional statement executes from left to right. It is not only an efficient solution but also a time-saving approach to use this ternary operator.

Syntax


(Condition) ? (Statement1) : (Statement2);

 

How to check whether a number is odd or even using a ternary operator in PHP?

In this program, we are checking whether a number is odd or even using a ternary operator. First, we have to accept the number from the user and assign it to the variable num and  then we have to perform the ternary operation check condition '$num % 2 == 0' if true assign "The entered number is an even number " otherwise "The entered number is an odd number " to the variable checkNum and at last we can print the value of the variable checkNum as the result

ALGORITHM

Step 1: Accept the number from the user and assign it to the variable num

Step 2: Perform the ternary operation check condition '$num % 2 == 0' if true assign "The entered number is an even number " otherwise "The entered number is an odd number " to the variable checkNum

Step 3: Print the value of the variable checkNum

PHP Source Code

                                          <?php
$num = readline("Enter the number: ");
$checkNum = $num % 2 == 0 ? "The entered number $num is an even number " : "The entered number $num is an odd number ";
echo $checkNum;
?>
                                      

OUTPUT

Example 1
Enter the number: 6
The entered number 6 is an even number

Example 2
Enter the number: 5
The entered number 5 is an odd number