tags:

views:

213

answers:

5

The code is this one:

$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 somebody explain me exactly what it is? Look like an Alternative syntax but I haven't managed to find infos.

Thanks you

+24  A: 

This is a ternary operator (scroll a bit to "Ternary Operator"):

The expression (expr1) ? (expr2) : (expr3) evaluates to expr2 if expr1 evaluates to TRUE, and expr3 if expr1 evaluates to FALSE.

Anton Gogolev
might be worth mentioning that ternary operators are not unique to PHP - see http://en.wikipedia.org/wiki/Ternary_operation
Dror
+1  A: 

It's what PHP insists on calling the "ternary operator" - see http://www.phpbuilder.com/manual/language.operators.comparison.php for syntax and example.

anon
+4  A: 

It means: if value is "" (empty), then set to "-" (hyphen), else set to whatever it is.

Just read a?b:c as «if a then b else c».

Ilya Birman
+3  A: 

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

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

instead of

if ($condition)
{
    $myvar = $valueIfTrue;
}
else
{
    $myvar = $valueIfFalse;
}
tharkun
A: 

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

i.e a == b ?? c so if a=b is true use a else use c

renegadeMind