user3733831
user3733831

Reputation: 2926

How I add a CSS class to first element of an array in PHP?

I am trying to select some images from mysql and need to store result in an array.

This is my WHILE loop so far:

// Fetch all the records:
while ($stmt->fetch()) {
        $result  = "<div class='item'>\n";
        $result .= "    <div class='gallery_image'>\n";
        $result .= "        <a class='thumbnail lightbox' title='{$db_restaurant_name}' rel='gal' target='_blank' href='{$image_path}{$image}'>\n";
        $result .= "            <div class='img-holder' style='background-image:url({$image_path}{$image})'></div>\n";
        $result .= "        </a>\n";
        $result .= "    </div>\n";
        $result .= "</div>\n";  
        $gallery[] = $result;   
    }  
}

My question is, I want to add a CSS class named active to first element of this $gallery array. This class need to be add to this line <div class='item'>\n"; Like this class="item active"

UPDATE:

$count = 0; 
// Fetch all the records:
while ($stmt->fetch()) {
    if($image_type == 0) {
        $class = '';
        if($count === 0) {
            $class = ' active';
        }

        $result  = "<div class='item {$class}'>\n";
        $result .= "    <div class='gallery_image'>\n";
        $result .= "        <a class='thumbnail lightbox' title='{$db_restaurant_name}' rel='gal' target='_blank' href='{$image_path}{$image}'>\n";
        $result .= "            <div class='img-holder' style='background-image:url({$image_path}{$image})'></div>\n";
        $result .= "        </a>\n";
        $result .= "    </div>\n";
        $result .= "</div>\n";  
        $gallery[] = $result;   

    }
    $count++;       
}  

Can anybody tell me how I do this?

Thank you.

Upvotes: 1

Views: 1470

Answers (2)

Dorian
Dorian

Reputation: 211

The easiest way to do this is to create a counter variable like :

$i = 0;
while ($stmt->fetch()) {
    $result  = "<div class='item " . (0 == $i ? "active" : "") . "'>\n";
    // ...
    $i ++;
} 

Upvotes: 0

t.h3ads
t.h3ads

Reputation: 1878

You can add a counter variable:

$count = 0;
while ($stmt->fetch()) {
    $class = '';
    if($count === 0) {
        $class = ' active';
    }
    $result  = "<div class='item" . $class . "'>\n";
    $result .= "    <div class='gallery_image'>\n";
    $result .= "        <a class='' title='' href='{$image_path}{$image}'>\n";
    $result .= "            <div class='' style='background-image:url({$image_path}{$image})'></div>\n";
    $result .= "        </a>\n";
    $result .= "    </div>\n";
    $result .= "</div>\n";  
    $gallery[] = $result;  
    $count++;
}

Upvotes: 2

Related Questions