Ternary Operator in PHP
Let's say we have the following code that checks
whether the user is already 18 years old or not:
<?php
$age = 17;
if ($age >= 18) {
$adult = true;
} else {
$adult = false;
}
var_dump($adult);
?>
As you can see, the if-else construct
is only needed to write a specific
value to the variable $adult. For
such tasks, when in a condition we only
set one variable, there is
a shorter solution using the so-called
ternary operator.
Its syntax is as follows:
<?php
variable = condition ? value1 : value2;
?>
The operator works as follows: if the condition is true,
then value1 is returned, otherwise
- value2. Let's rewrite
the code from the very beginning of the lesson using
the ternary operator:
<?php
$age = 17;
$adult = $age >= 18 ? true: false;
var_dump($adult);
?>
By the way, you can avoid writing the result to
a variable and immediately output it via var_dump:
<?php
$age = 17;
var_dump( $age >= 18 ? true: false );
?>
The ternary operator should only be used in the simplest cases, as its use makes the code harder to understand.
Let a variable $num be given, which
can be either negative or positive.
Write into the variable $res the number
1 if the variable $num is greater
than or equal to zero, and the number -1 if the variable
$num is less than zero.