olo
olo

Reputation: 5271

Assign different HTML classes to elements in a PHP array

I am working on some images and want to assign different classes to them in batch.

here is my simple code

$image_dir = 'images';
$showimage = scandir($image_dir, 0);
unset($showimage [0],$showimage [1]);
print_r ($showimage );

the result is

Array ( 
    [2] => exmapleiamge1.png 
    [3] => exmapleiamge1_1.png 
    [4] => exmapleiamge1_2.png 
    [5] => exmapleiamge2_1.png 
    [6] => exmapleiamge2_2.png 
    [7] => exmapleiamge2_3.png 
    [8] => exmapleiamge3_1.png 
    [9] => exmapleiamge3_2.png 
)

What I want to achieve is that, assign div class=no1 to all images from exmapleiamge1_1 to exmapleiamge1_2, and assign class=no2 images from exmapleiamge2_1 to exmapleiamge2_3, and also for class no3.... etc;

I think the key is to filter the numbers, is it possible someone could give me a hand as I am a php beginner and keen to learn how to do that.

Many thanks in advance

Upvotes: 0

Views: 345

Answers (1)

uzyn
uzyn

Reputation: 6693

Here's one way you can do it:

foreach ($showimage as $image) {
    // Extract the number first
    $no = substr($image, strlen('exmapleiamge'), 1);

    $class = 'no'.$no;

    // Echo the HTML elements
    echo "<div class='$class'>";
    echo "<img src='$image'>";
    echo "</div>";
}

Upvotes: 2

Related Questions