Glen Keybit
Glen Keybit

Reputation: 326

Adding an incrementing prefix (html tag) and closing (html tag) suffix in a PHP foreach loop

I'm using a simple PHP foreach loop to display (in plain text) the url for each file (images in this case) found in a directory.

Here is the (working) code for that..

<?php
$directory = "imguploader/UploadFolder";
$images = glob($directory . "/*.png");

foreach($images as $image)
{
  echo "http://www.myurl.com/".$image."<br />";
}
   ?>

Any this quite nicely almost does what I need, current results are like this..

http://www.myurl.co.uk/imguploader/UploadFolder/lp1-hot-pink.png

http://www.myurl.co.uk/imguploader/UploadFolder/lp2-green.png

http://www.myurl.co.uk/imguploader/UploadFolder/lp3-purple.png

But what I now need to do is add an (auto incrementing) html tag (as executing html, not txt) eg <div id="img1">, <div id="img2">, <div id="img3"> etc to the start of each line, then the closing </div> tag to the end of each line the foreach creates.

Is this possible?

Upvotes: 0

Views: 76

Answers (2)

Anand Pawar
Anand Pawar

Reputation: 1

Use this code

<?php
    $directory = "imguploader/UploadFolder";
    $images = glob($directory . "/*.png");
    $i = 0;
    foreach($images as $image) {
        $i++;
        echo "<div id='img".$i."'>";
            echo "http://www.myurl.com/".$image."<br />";
        echo "</div>";
    }
?>

Upvotes: 0

Leon Kunštek
Leon Kunštek

Reputation: 563

Try this:

<?php
    $directory = "imguploader/UploadFolder";
    $images = glob($directory . "/*.png");
    $num = 0;

    foreach($images as $image) {
        $num++;
        echo "<div id=\"img".$num."\">http://www.myurl.com/".$image."</div><br />";
    }
?>

I've tested the above example and it works.

Upvotes: 1

Related Questions