Michiel
Michiel

Reputation: 8083

CSS depends on result PHP if-statement

I wrote a little script where an item should be bold whenever a certain value is set to 0. But I have the feeling I'm repeating myself... Is there a way to avoid this repeat?

$output .= '<td>';
if ('0' == $value['treated']) {
    $output .= '<b>';
}
$output .= $value['from'];
$output .= substr($value['message'], 20);
if ('0' == $value['treated']) {
     $output .= '</b>';
}
$output .= '</td>';

Upvotes: 0

Views: 168

Answers (5)

jgroenen
jgroenen

Reputation: 1326

$dom = new DOMDocument;
$dom->loadHTML('<html/>');
$body = $dom->documentElement->appendChild($dom->createElement('body'));
for ( $i = 0; $i < 100; ++$i ) {
    $div = $body->appendChild($dom->createElement('div'));
    if ( rand() % 2 ) {
        $div->setAttribute('class', 'highlighted');
        $div->nodeValue = 'bold';
    } else {
        $div->nodeValue = 'normal';
    }
}
die($dom->saveHTML());

Upvotes: 0

Miqdad Ali
Miqdad Ali

Reputation: 6147

This is a simple way you can acheive

$output .= '<td>';
        $bs = '';
        $be = '';
        if ('0' == $value['treated']) {
            $bs = '<b>';
            $be = '</b>';
        }
        $output .= $bs;
        $output .= $value['from'];
        $output .= substr($value['message'], 20);
        $output .= $be;
    $output .= '</td>';   

or

$output .= '<td';
    if ('0' == $value['treated']) {
        $output .=' style="font-weight:bold;"';
    }
    $output .= '>';
    $output .= $value['from'];
    $output .= substr($value['message'], 20);
$output .= '</td>';

Upvotes: 0

Daniel
Daniel

Reputation: 3806

I don't know if this is what you are looking for, but you could buffer the contents:

$output .= "<td>";
$buffer = $value['from'];
$buffer = substr($value['message'], 20);
$output .= ('0' == $value['treated'])
    ? "<b>" . $buffer . "</b>"
    : $buffer;

Edit: I see deceze was first :)

Upvotes: 0

deceze
deceze

Reputation: 522085

$output = $value['from'] . substr($value['message'], 20);

if ('0' == $value['treated']) {
    $output = "<b>$output</b>";
}

$output = "<td>$output</td>";

Upvotes: 1

Gavin
Gavin

Reputation: 6394

You could set a class instead?

$output .= '<td' . ('0' == $value['treated'] ? ' class="bold"' : '') . '>';
$output .= $value['from'];
$output .= substr($value['message'], 20);
$output .= '</td>';

All you would then need to do is add

.bold { font-weight: bold; }

to your css file

Upvotes: 5

Related Questions