php if 语句在连接中间?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13089747/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
if statement in the middle of concatenation?
提问by VVV
Does this not work? or am I just doing it wrong? Tried multiple variations of it, and can't seem to find any solid info on the subject. any ideas?
这不起作用吗?还是我只是做错了?尝试了它的多种变体,似乎无法找到有关该主题的任何可靠信息。有任何想法吗?
$given_id = 1;
while ($row = mysql_fetch_array($sql))
{
if ($i < 10){
$display = '<a href="' . $row['info'] . '" onMouseOver="' . if($row['type']=="battle"){ . 'showB' . } else { . 'showA'() . "><div class="' . $row['type'] . "_alert" . '" style="float:left; margin-left:-22px;" id="' . $given_id . '"></div></a>';
回答by Sony Mathew
if is a self standing statement. It's a like a complete statement. So you can't use it in between concatenetion of strings or so. The better solution is to use the shorthand ternary operatior
如果是一个独立的声明。这就像一个完整的陈述。所以你不能在字符串的串联之间使用它。更好的解决方案是使用速记三元运算符
(conditional expression)?(ouput if true):(output if false);
This can be used in concatenation of strings also. Example :
这也可以用于字符串的串联。例子 :
$i = 1 ;
$result = 'The given number is'.($i > 1 ? 'greater than one': 'less than one').'. So this is how we cuse ternary inside concatenation of strings';
You can use nested ternary operator also:
您也可以使用嵌套的三元运算符:
$i = 0 ;
$j = 1 ;
$k = 2 ;
$result = 'Greater One is'. $i > $j ? ( $i > $k ? 'i' : 'k' ) : ( $j > $k ? 'j' :'k' ).'.';
回答by deceze
if..elseis a statementand cannot be used inside an expression. What you want is the "ternary" ?:operator: http://php.net/manual/en/language.operators.comparison.php#language.operators.comparison.ternary.
if..else是一个语句,不能在表达式中使用。你想要的是“三元”?:运算符:http: //php.net/manual/en/language.operators.comparison.php#language.operators.comparison.ternary。
回答by doublesharp
Use a shorthand if statement using ternary operators ?:-
使用三元运算符使用速记 if 语句?:-
$display = 'start ' . (($row['type']=="battle")? 'showB' : 'showA') . ' end ';
See "Ternary Operators" on http://php.net/manual/en/language.operators.comparison.php
请参阅http://php.net/manual/en/language.operators.comparison.php上的“三元运算符”
回答by Ignacio Vazquez-Abrams
ifis a statement. One cannot put statements inside an expression.
if是一个声明。不能将语句放入表达式中。
$str = 'foo';
if (cond)
{
$str .= 'bar';
};
$str .= 'baz';

