T
T
tatarrr952021-07-31 20:57:00
PHP
tatarrr95, 2021-07-31 20:57:00

How will the entry from JS “value = value || 0"?

In js, there is such a nice variable assignment, which means that if value exists, we take the value from value, otherwise we set it to 0. Is there such a short notation in php without any isset / empty?
value = value || 0

Answer the question

In order to leave comments, you need to log in

4 answer(s)
S
Sergey, 2021-07-31
@tatarrr95

$value = $value?? 0
no?

V
Vitsliputsli, 2021-07-31
@Vitsliputsli

if value exists, take value from value, otherwise set to 0.

$value = $value ?? 0
as already suggested, but it has nothing to do with it. || is a disjunction operator, but in php it returns a bool type, unlike in js.
value = value || 0

Z
zersoulg, 2021-08-05
@zersoulg

$value1 = $value2 ?? 0;
would be equivalent

if (isset($value2)) {
     $value1 = $value2;
} else {
     $value1 = 0;
}

which means: if the variable $value2 exists or it is not equal to Null, then we assign $value1 to $value2, otherwise we assign $value1 to 0
In PHP, without specifying special characters, you can use only in conditional statements, for example,
if ($test) {
    ...
] else {
    ...
}

will be equivalent , that is, a non-strict comparison will be applied
$test == true ? ... : ...;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question