$row['vendorID'], "n...">

I came across this syntax: var == "?" - ": var. Can someone explain?

The code is as follows:

$vendors[] = array(
    "id" => $row['vendorID'],
    "name" => $row['name'] == "" ? "-" : $row['name'],
    "tel1" => $row['phone1'] == "" ? "-" : $row['phone1'],
    "tel2" => $row['phone2'] == "" ? "-" : $row['phone2'],
    "mail" => $row['email'] == "" ? "-" : $row['email'],
    "web" => $row['web'] == "" ? "-" : $row['web']);

Can someone explain to me what it is? See Alternate Syntax , but I could not find the information.

thank you

+3
source share
5 answers

This is the ternary operator :

An expression (expr1) ? (expr2) : (expr3)takes a value expr2if it expr1takes a value TRUEand expr3if it expr1takes a value FALSE.

+24
source

This means: if the value is "(empty), then set the value to" - "(hyphen), otherwise set its value.

a? b: c "if a then b else c".

+4

Yes, this is what others say, but it is not recommended in terms of code readability. Use it with care and do not use it without brackets around the condition.

$myvar = ($condition == TRUE) ? $valueIfTrue : $valueIfFalse;

instead

if ($condition)
{
    $myvar = $valueIfTrue;
}
else
{
    $myvar = $valueIfFalse;
}
+3
source

This is what PHP insists on calling the "triple operator" - see http://www.phpbuilder.com/manual/language.operators.comparison.php for syntax and example.

+1
source

You can also do it like "name" => $row['name'] == "" ?? "-"

ie a == b ?? c, so if a = b is true, use else using c

0
source

Source: https://habr.com/ru/post/1707751/


All Articles