user2869402 user2869402 - 6 months ago 3
PHP Question

How to write if statement inside a string in php?

I want to write an

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

$sql = mysql_query("SELECT * FROM `reports` ORDER BY `id` DESC");
$reports_count = mysql_num_rows($sql);
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']));
<td><a href='view_report.php?id=$id'>View Report Message</a></td>
<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>'.

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


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.