0

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

1 Answer 1

2

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>";
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.