Explain the use of ‘?’ Operator in PHP

May 7, 2023 · Team EasyExamNotes · 2 min read (est.) · 0 comments

Share on WhatsApp

The ‘?’ operator in PHP is called the ternary operator, also known as the conditional operator. It is a shorthand way of writing an if-else statement in a single line.

The syntax of the ternary operator is as follows:

condition ? true-expression : false-expression;

Here, condition is the condition that we want to check. If the condition is true, true-expression is executed, and if the condition is false, false-expression is executed.

For example, consider the following code:

$age = 20;
$isAdult = ($age >= 18) ? true : false;

if ($isAdult) {
    echo "You are an adult";
} else {
    echo "You are not an adult";
}

In this code, we define a variable $age with a value of 20. We then use the ternary operator to check if $age is greater than or equal to 18. If it is, the expression true is assigned to the variable $isAdult, otherwise the expression false is assigned to $isAdult.

Finally, we use an if-else statement to check the value of $isAdult, and output a message based on whether the person is an adult or not.

The ternary operator can be a useful tool for simplifying code, particularly in cases where you need to assign a value to a variable based on a single condition. However, it can also make code harder to read and understand if overused or used excessively.

Discussion

Ask a question, share your thoughts or report an error.

Sign in to participate in the discussion.

Join the discussion