Shorted if - ternary operator PHP. Code example open

Shorted if - ternary operator PHP. Code example

Approved. Code works!
This is exactly the working code that is verified by the moderator or site administrators
Tested: PHP 5.6 +

There is a construct in PHP that is similar in effect to the if-else construct, but is also an expression. It’s called the ternary operator.

The ternary operator works in much the same way as the if statement, but when using the ternary operator, we write ? and :.

$speed = 55;
echo ($speed <= 60) ? "Normal speed" : "speed exceeded !"; 

Example to use the option when you need to change the value of a variable, only in the case when the variable being checked is not equal to true:

$var = $value ?: "Another value";

This option is useful if you need to first check whether a variable exists. That is, if the variable does not exist, then use some other value:

$var = $value ?? "Something else";
//same as
$var = isset($value) ? $value : "Something else";

The main difference between expressions $var = $value ?? “Something else”; and $var = $value ?: “Another value”; lies in how they handle values that may be false.

In the expression $var = $value ?? “Something else”; , the union operator with null ( ?? ) checks whether $value is null. If $value is null, then $var will be set to “Something else“. However, if $value is not null, even if its value is false (for example, 0 or an empty string), then the value of $value will be assigned to the variable $var.
0

More

Leave a Reply

Your email address will not be published. Required fields are marked *

How many?: 22 + 22

lil-code© | 2022 - 2024
Go Top
Authorization
*
*
Registration
*
*
*
*
Password generation