Skip to content
Advertisement

How to display a column of data when the parent variable might not be declared?

I am generating some dynamic content in the view layer of my codeigniter project.

<td class="<?php echo empty($log->category) ? "noactioncell" :''; ?> text-center align-middle">
<?php echo !empty($log->category) ? foreach($log->category as $c):echo $c->category_name."<br/>"; endforeach; : '';?></td>

The trouble is, I am getting the following error in my ternary expression:

Parse error: syntax error, unexpected token “foreach”

How can I display the looped category_name data separated by <br/> tags without generating this error when $log->category is not declared?

Advertisement

Answer

The code you have posted is coded wrong way. The right and more readable variant will be like this:

<td class="<?php echo empty($log->category) ? "noactioncell" :''; ?> text-center align-middle">
<?php 
    if(!empty($log->category)){
        foreach($log->category as $c){
            echo $c->category_name."<br/>"; 
        }
    }
?>
</td>

Here is a good explanation:

The ternary operator takes 3 expressions in the form of (expr1) ? (expr2) : (expr3).

continue (or foreach in your case) is a control structure statement, not an expression. And hence, it can’t be an operand of the ternary operator. In fact, none of PHP’s operators accept control structures as operands, as far as I’m aware. The same applies to the rest of the broad C-family languages as well.

And for the sake of readability, it is probably better to use an if statement in your case.

By @Fabrício Matté How to use continue keyword in a ternary operator in php

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement