Paul
Paul

Reputation: 3368

Adding background color to element within php if-statement

I have the following code in which I want to add an element to my if statement, but I am unsure how to approach this. What I am looking to do is add a background-color to the else part of it. Within this:

else {
        $status_img = '<img src="../icons/collection/checkmark.png" alt="Goal Complete">';
}

So if $status is not 0, I want to set background color for the class goal-box-right.

Is there anyway I can manipulate the CSS through php like this?

foreach ($rows as $row) {
            $status = $row['status'];
            if ($status == 0) {
                $status_img = '<img src="../icons/collection/x-sign.png" alt="Goal Not Complete">';
            }
            else {
                $status_img = '<img src="../icons/collection/checkmark.png" alt="Goal Complete">';
            }
            $goal_date = $row['date'];
            $fixed_goal_date = fixDate($goal_date);
            $html = "";
            $html .= '<div class="goal-box" id="comment-'.$row['id'].'">';
            $html .= '<div class="goal-box-left">'; //added
            $html .= '<div class="goal-post-status">'.$status_img. '</div>';
            $html .= '</div>'; //added
            $html .= '<div class="goal-box-right">'; //added
            $html .= '<div class="goal-post-title">'.$row['title']. '</div>';
            $html .= '<div class="goal-post-date">'.$fixed_goal_date. '</div>';
            $html .= '<div class="goal-post-description">'.$row['description']. '</div>';
            $html .= '</div>'; //added
            $html .= '</div>';

Upvotes: 1

Views: 210

Answers (2)

bcmcfc
bcmcfc

Reputation: 26765

Separate the logic - add a CSS class based on the status then set the colours in the stylesheet.

$class = $status != 0 ? 'status-nonzero' : '';

$html .= '<div class="goal-box-right ' . $class . '">';

CSS:

.goal-box-right.status-nonzero { background-color: #foo }

Advantage is keeping the style logic in the CSS where it belongs and away from the code that's generating the HTML.

Upvotes: 2

u_mulder
u_mulder

Reputation: 54841

So what's the problem:

$style = '';
if ($status == 0) {
    $style = ' style="your-style:here"';
    $status_img = '<img src="../icons/collection/x-sign.png" alt="Goal Not Complete">';
}
else {
    $status_img = '<img src="../icons/collection/checkmark.png" alt="Goal Complete">';
}

// ...
$html .= '<div class="goal-box-right"' . $style . '>'; //added

Upvotes: 0

Related Questions