user2869402 user2869402 - 7 months ago 9
PHP Question

How to write if statement inside a string in php?

I want to write an

if
statement inside a string variable, it goes like this :-

$report_list="";
$sql = mysql_query("SELECT * FROM `reports` ORDER BY `id` DESC");
$reports_count = mysql_num_rows($sql);
if($reports_count>0){
while($row = mysql_fetch_array($sql)){
$id = $row['id'];
$by = $row['by'];
$title = $row['title'];
$message = $row['message'];
$date = strftime("%d- %b- %Y",strtotime($row['date']));
$reports_list.="<tr>
<td>$by</td>
<td>$title</td>
<td>$date</td>
<td><a href='view_report.php?id=$id'>View Report Message</a></td>
<td>
if(file_exists('reports/$id.xlsm')){
<a href='reports/$id.xlsm' download>Download Attached File</a>'.
} else if(file_exists('reports/$id.xlsx')){
<a href='reports/$id.xlsx' download>Download Attached File</a>'.
}
</td>
</tr>";


how can i make this code works? how can i write these
if
statements properly?

Answer

You can do that using concatenation and ternary operator <cond> ? <if-true> : <if-false>:

$reports_list .= "<tr>...<td>"
              . (file_exists('reports/$id.xlsm')
                ? "<a href='reports/$id.xlsm' download>Download Attached File</a>" : "")
              . (file_exists('reports/$id.xlsx')
                ? "<a href='reports/$id.xlsx' download>Download Attached File</a>" : "")
              . "</td></tr>";

It is up to you to decide whether it is more or less readable than just using several if statements -- this way is suggested more for shorter and simpler conditions.

Comments