2

我不知道为什么会收到 Parse error: syntax error, unexpected T_IF on line 6。

 $sf = array ( 

            "name" => $firstname . ' ' . $lastname,
            "email" => $email,
            "address" => $shipping_address_1 . if(!empty($shipping_address_2 )) { echo ", " . $shipping_address_2 }
            );
            print_r($sf);

我想检查 $shipping_address_2 是否不为空,如果不是,则显示它。

4

3 回答 3

2

因为你的代码是错误的。您不能if在数组初始化中放置语句。

于 2012-05-10T20:41:30.333 回答
2

不是 100% 确定,但你应该能够使用三元运算符......

"address" => $shipping_address_1 . 
    (!empty($shipping_address_2 )) ? 
        ", " . $shipping_address_2 : // This gets executed if condition is true
        ""    // This gets executed if the condition is false
于 2012-05-10T20:41:46.373 回答
1

代替

 "address" => $shipping_address_1 . if(!empty($shipping_address_2 )) { echo ", " . $shipping_address_2 }

"address" => $shipping_address_1 . (empty($shipping_address_2) ? null :  ", " . $shipping_address_2)
于 2012-05-10T20:42:09.243 回答