Ternary operators in PHP are shorthand conditional statements that allow you to write a simple if-else statement in a single line of code. The syntax for a ternary operator is:
(condition) ? true_value : false_value;
If the condition is true
, the true_value
is returned. Otherwise, the false_value
is returned.
For example, the following code:
$num = 5;
$result = ($num > 10) ? "greater than 10" : "less than or equal to 10";
echo $result;
will output “less than or equal to 10” because the condition $num > 10
is false
.
Ternary operators can make code more concise and easier to read. Still, they should be used sparingly and only in cases where the conditions and values are simple and easy to understand.
Echo Inline
You can directly echo the ternary operator like this:
$num = 5;
echo ($num > 10) ? "greater than 10" : "less than or equal to 10";
In this example, the ternary operator is directly echoed without assigning it to a variable first.
Both of these examples will output “less than or equal to 10” because the value of $num
is less than 10.
Adding a class is a handy time to use this sort of thing:
$dark_mode = 'yes';
<div class="author-card <?php echo ( 'yes' === $dark_mode ) ? 'author-card-dark-mode' : 'author-card-light-mode'; ?>">
Null coalescing operator
The Null coalescing operator (??) in PHP is used to check if a variable is null and provide a default value if it is. It is a shorthand way of writing an if-else statement.
The syntax is:
$variable = $value ?? $default_value;
This means that if $value
is not null, $variable
will be assigned the value of $value
. If $value
is null, $variable
will be assigned the value of $default_value
.
For example:
$name = $user['name'] ?? 'Guest';
In this example, if $user['name']
is not null, $name
will be assigned the value of $user['name']
. If $user['name']
is null, $name
will be assigned the value of ‘Guest.’