首页 > 解决方案 > 有没有办法在变量中包含 if 语句?

问题描述

我试图在 php 变量中提出一个 IF 语句,然后返回该变量,但我收到一个错误:语法错误,意外的 'if' (T_IF)

      $output .= '<tr>  
                      <td>'.$row["case_no"].'</td>  
                      <td>'.$row["description"].'</td>  
                      <td>'.$row["claimant"]." VS ".$row["defendant"].'</td>  
                      <td>'. if($row["court_date_assigned"] == 1){ echo "result" } .'</td>
                      <td>'.$row["court_date_assigned"].'</td> 
                      <td>'.$row["court_date_assigned"].'</td> 
                      <td>'.$row["court_date_assigned"].'</td>  
                 </tr>  
                      ';  
  }  
  return $output; 

标签: php

解决方案


您可以使用三元运算符,并假设您在 $row['court_date_assigned'] 中有一个 bool,您可以使用严格匹配(因此类型也必须匹配)。更多信息:https ://www.php.net/manual/en/language.operators.comparison.php#language.operators.comparison.ternary

您还混合了双引号和单引号(围绕“VS”)。

$output .= '
<tr>  
  <td>'.$row['case_no'].'</td>  
  <td>'.$row['description'].'</td>  
  <td>'.$row['claimant'].' VS '.$row['defendant'].'</td>  
  <td>'.($row['court_date_assigned'] === 1 ? $result : '') .'</td>
  <td>'.$row['court_date_assigned'].'</td> 
  <td>'.$row['court_date_assigned'].'</td> 
  <td>'.$row['court_date_assigned'].'</td>  
</tr>';  

推荐阅读