Ternary and mod operator in php

Using the if-else and switch case is an essential part of programming for evaluating conditions. We always look for shortcuts everywhere whether it is a route for traveling or game or code. In this Ternary Operator PHP, we will see how it is used for shortening conditional statements.

What is Ternary operator?

The ternary operator is a conditional operator that decreases the length of code while performing comparisons and conditionals. This method is an alternative for using if-else and nested if-else statements. The order of execution for this operator is from left to right. Obviously, it is the best case for a time-saving option.

It also produces an e-notice while encountering a void value with its conditionals. It is called a ternary operator because it takes three operands – a condition, a result for true, and a result for false.

Syntax:

[Condition] ? [Statement1] : [Statement2];
  • Condition: It is the expression to be evaluated which returns a boolean value.
  • Statement 1: it is the statement to be executed if the condition results in a true state.
  • Statement 2: It is the statement to be executed if the condition results in a false state.

Example program to whether student is pass or fail:


Output:

pass

When do we use Ternary Operator?

We use ternary operator when we need to simplify if-else statements that are used to assign values to variables. Moreover, it is commonly used when we assign post data or validate forms.

Let’s say, we were programming a login form for a college university where we wanted to ensure that the user entered their registration number provided by the university then we could move further.

//if the registration number is not specified, notify the customer
$reg_number = [isset[$_POST['reg']]] ? $_POST['reg'] : die['Please enter your registration number'];

Let’s look at an example of a validation form for better understanding:

Chủ Đề