doushang1964
2009-05-06 10:41
浏览 22
已采纳

我遇到过这种语法:var ==“”? “ - ”:var。 有人可以解释一下吗?

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

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

5条回答 默认 最新

  • doucheng8471 2009-05-06 10:44
    已采纳

    This is a ternary operator:

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

    点赞 打赏 评论
  • dto5637 2009-05-06 10:45

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

    点赞 打赏 评论
  • dsadsadsa1231 2009-05-06 10:46

    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».

    点赞 打赏 评论
  • duanliang8464 2009-05-06 11:29

    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;
    }
    
    点赞 打赏 评论
  • dpp10181 2009-05-06 13:50

    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

    点赞 打赏 评论

相关推荐 更多相似问题