Is it possible to insert if else statement on for each
I would like to do add some if else statement on my for each.
I just want to set no value data to display as None.
and if it has value then it will return the data.
TABLE : wp_events_answer
╔════╦══════════════╦════════════╗
║ id ║ answer ║question_id ║
╠════╬══════════════╬════════════╣
║ 1 ║ Maybank ║ 12 ║
║ 2 ║ no value ║ 12 ║
║ 3 ║ no value ║ 12 ║
║ 4 ║ CIMB ║ 12 ║
╚════╩══════════════╩════════════╝
=
$number = 1;
foreach ($datas as $data) {
$result .= '<tbody>';
$result .= '<tr>';
$result .= '<td>';
$result .= $number++;
$result .= '</td>';
$result .= '<td>';
$result .= $data->fname;
$result .= ' ';
$result .= $data->lname;
$result .= '</td>';
$result .= '<td>';
//#### PLEASE TAKE A LOOK HERE #####
if($result .= '')
{
$result .= 'None';
}
else
{
$result .= $data->answer;
}
// #### END ####
$result .= '</td>';
}
$result .= '</tr>';
$result .= '</table>';
return $result;
Use this
if(empty($data->answer))
{
$result .= 'None';
}
else
{
$result .= $data->answer;
}
if( $result .= '')
should be if( !$data->answer)
.
If you're pedantic, you'd write if( $data->answer === '')
but... well it's a bit silly in my opinion.
You have your condition wrong. The statement $result .= ''
is not a comparison and (if PHP does what I think it does) always returns true
. Instead, change it to if( $data->answer == "" )
(or something like that) to actually compare your answer with an empty value.
I suspect your trying todo something like this (if not show expected HTML output and ill update):
<?php
$number = 1;
$result = '
<table>
<tbody>'.PHP_EOL;
foreach ($datas as $data) {
//if $data->answer not empty
if(!empty($data->answer)){
$result .= '
<tr>
<td>'.($number++).'</td>
<td>'.htmlspecialchars($data->fname).' '.htmlspecialchars($data->lname).'</td>
<td>'.$data->answer.'</td>
</tr>'.PHP_EOL;
}
//
else{
$result .= '
<tr>
<td colspan="3">None</td>
</tr>'.PHP_EOL;
}
}
$result .= '
</tbody>
</table>';
// returning from a function?
//return $result;
echo $result;
?>
You really went to town on the concatenation feature of PHP, took a while to understand what you are trying todo. Hope it helps ;p