Unexpected close parenthesis in ternary operator PHP

120 Views Asked by At

I have a ternary operator which will echo styles for an HTML tag. I have tried erasing or adding parentheses but there's still an error.

foreach( $result as $row ) {
    $us = $row['username'];
    echo '<div id="msg_guest" style="'.($us != 'Admin' ? ($us != 'inTELLigence' ? 'float: right; background-color: #51b8c1':'float: left;')).'"><div id="usr" style="'.($us != 'Admin' ? ($us != 'inTELLigence'? 'background-color: #67d5de':'background-color: #e6898a')).'"><div id="user">'.$row['username']. '</div><div id="time">'.$row['time_now'].'</div></div><p id="msg"> '.$row['message'].'</p></div><br />';
}
2

There are 2 best solutions below

2
On BEST ANSWER

You have not close condition completely for your first statement near left;')) you actually need left;') : '')

Replace

echo '<div id="msg_guest" style="'.($us != 'Admin' ? ($us != 'inTELLigence' ? 'float: right; background-color: #51b8c1':'float: left;')).'"><div id="usr" style="'.($us != 'Admin' ? ($us != 'inTELLigence'? 'background-color: #67d5de':'background-color: #e6898a')).'"><div id="user">'.$row['username']. '</div><div id="time">'.$row['time_now'].'</div></div><p id="msg"> '.$row['message'].'</p></div><br />';

with

echo '<div id="msg_guest" style="'.( $us != "Admin" ? ($us != "inTELLigence" ? "float: right; background-color: #51b8c1":"float: left;") : '' ).'"><div id="usr" style="'.( $us != "Admin" ? ($us != "inTELLigence" ? "background-color: #67d5de":"background-color: #e6898a") : '').'"><div id="user">'.$row['username']. '</div><div id="time">'.$row['time_now'].'</div></div><p id="msg"> '.$row['message'].'</p></div><br />';
0
On

You should avoid nesting ternary operators as it can get quite messy quickly.

Your problem in this instance however is because you have a syntax error with the parent ternary statements. They do not have the else defined.

e.g. you need to end it with :

$trueBoolean ? 'true condition' : 'false condition';

Try something like this.

foreach( $result as $row ) {
    $us = $row['username'];

    $html = '';
    if ($us != 'Admin') {
        $html = $us != 'inTELLigence' ? 'float: right; background-color: #51b8c1' : 'float: left;';
    }

    $html2 = '';
    if ($us != 'Admin') {
        $html2 = $us != 'inTELLigence' ? 'background-color: #67d5de' : 'background-color: #e6898a';
    }

    echo '<div id="msg_guest" style="'. $html .'"><div id="usr" style="'. $html2 .'"><div id="user">'.$row['username']. '</div><div id="time">'.$row['time_now'].'</div></div><p id="msg"> '.$row['message'].'</p></div><br />';
}