2017-03-09 57 views
0

我試圖把下面的內容放在一個php變量中。如果變量裏面的語句

我不知道我在做什麼錯在這裏:

$cartlink='<a class="cart-contents" href="'.$shoppingcart.'" title="View your shopping cart">' + if ($count > 0) {<span class="cart-contents-count">"'.$count.'"</span></a>} + '</a>'; 
+0

[PHP的可能的複製,速記,如果..使用三元運算符](http://stackoverflow.com/questions/29814065/php-shorthand-if-else-using-ternary-operators) – ShiraNai7

+1

你是否有經驗的PHP:| – Andrew

+2

@安德魯不,他不是 –

回答

0

你的字符串連接是有點過了,和PHP使用點.到Concat的變量在一起,不+像JavaScript。

有一對夫婦的,你可以做到這一點的方式,通過一個三元操作

$cartlink = '<a class="cart-contents" href="'.$shoppingcart.'" title="View your shopping cart">'.($count > 0 ? '<span class="cart-contents-count">"'.$count.'"</span></a>' : "").'</a>'; 

或字符串concatination通過正常的,如果

$cartlink = '<a class="cart-contents" href="'.$shoppingcart.'" title="View your shopping cart">'; 
if ($count > 0) 
    $cartlink .= '<span class="cart-contents-count">"'.$count.'"</span></a>'; 
$cartlink .= '</a>'; 
0

你不能,如果這樣的語句中使用。相反,使用內嵌版本:(condition ? true_case : false_case)

您可以直接寫變量放到引號 echo "Value: $variable";

$cartlink="<a class='cart-contents' href='$shoppingcart' title='View your shopping cart'>" . ($count > 0 ? "<span class='cart-contents-count'>$count</span></a>" : "") . '</a>'; 

編輯:在PHP整個三元操作必須由括號包圍才能正常工作