PHP : Shorthand if Statements

In PHP, you can use shorthand versions of if statements to write more concise code when you have simple conditional expressions. These shorthand versions are often referred to as the ternary operator or the conditional operator. The syntax for the shorthand if statement is:


(condition) ? value_if_true : value_if_false;

This syntax evaluates the condition. If the condition is true, it returns value_if_true; otherwise, it returns value_if_false. Here's an example:


$age = 20;
$status = ($age >= 18) ? "adult" : "minor";
echo $status; // Outputs: adult

 

In this example, if the variable $age is greater than or equal to 18, it assigns the string adult to the variable $status; otherwise, it assigns the string minor.

You can also nest ternary operators to create more complex conditional expressions. However, nesting too many ternary operators can make the code less readable and harder to understand, so use them judiciously. Here's an example of nested ternary operators:


$number = 10;
$result = ($number > 0) ? (($number % 2 == 0) ? "even" : "odd") : "negative";
echo $result; // Outputs: even

 

In this example, if $number is greater than 0, it checks if it's even or odd using another ternary operator. If $number is negative, it assigns the string negative to $result.