我怎样才能使这个PHP条件?

时间:2013-06-14 18:27:08

标签: php operators

我试图让这个PHP表格单元格根据条件写一个颜色,但我遗漏了一些导致语法错误的东西?

以下是代码:

$table = '<table>
<tr>
 <th> Qty </th>
 <th> Length </th>
 <th> Description </th>
 <th> Color </th>
</tr>
<tr>
 <td></td>
 <td></td>
 <td>'.$gauge. ' &nbsp; ' .$panel.  '</td>'
 if ($sscolor == "None")
   {
         '<td>' .$color. '</td>';    
   }
       else
   {
         '<td>' .$sscolor. '</td>';
   }
   '</td>
</tr> ';

4 个答案:

答案 0 :(得分:1)

是。你不能在字符串中放入if / else条件。你可以使用三元组。

 $str = 'text'.($sscolor == 'None' ? $color : $sscolor).' more text'; // etc

否则你需要在if之前结束字符串,然后使用.=将其连接到它上面

答案 1 :(得分:0)

在向字符串写入字符串后,不能将IF条件放在变量中 我建议你这样做是怎么做的

if ($sscolor == "None")
   {
         $extra_string = '<td>' .$color. '</td>';    
   }
       else
   {
        $extra_string = '<td>' .$sscolor. '</td>';
   }
$table = '<table>
<tr>
 <th> Qty </th>
 <th> Length </th>
 <th> Description </th>
 <th> Color </th>
</tr>
<tr>
 <td></td>
 <td></td>
 <td>'.$gauge. ' &nbsp; ' .$panel.  '</td>' . $extra_string . '
</tr> ';

答案 2 :(得分:0)

问题是您需要在;语句之前用分号if关闭字符串连接。如果不这样做,则会出现语法错误:

<td>'.$gauge. ' &nbsp; ' .$panel.  '</td>' <-- Semicolon here
if ($sscolor == "None")                      <-- Syntax error, unexpected if token

避免这样的事情的一个好方法是使用heredoc字符串:

// Figure out the color before going into the string
if ($sscolor === 'None') {
  $color = $sscolor;
}
// heredoc string, with string interpolation
$table = <<< HTML
  <table>
    <tr>
      <th>Qty</th>
      <th>Length</th>
      <th>Description</th>
      <th>Color</th>
    </tr>
    <tr>
      <td>-</td>
      <td>-</td>
      <td>{$gauge} &nbsp; {$panel}</td>
      <td>{$color}</td>
    </tr>
  </table>
HTML;

详细了解strings

此外,即使是最优秀的PHP程序员也必须处理错误。这是学习PHP的一部分。所以,你应该养成使用谷歌搜索错误信息的习惯;它们很容易找到,你可以帮助自己并同​​时学习。

答案 3 :(得分:-1)

您需要连接if语句中的行。

<td>'.$gauge. ' &nbsp; ' .$panel.  '</td>';
 if ($sscolor == "None") {
    $table .= '<td>' .$color. '</td>';    
 } else {
     $table .= '<td>' .$sscolor. '</td>';
 }
$table .= '</td>';