Help with PHP foreach statment.

Status
Not open for further replies.

marcbraulio

Baseband Member
Messages
51
So I am building a Image Scroller in which the images are grabbed from a specific directory and display in a Jquery animated div, so managed to do that successfully using the following code:

PHP:
//path to directory to scan
$directory = "photos/";
 
//get all image files with a .jpg extension.
$images = glob("" . $directory . "{*.jpg,*.gif,*.png}", GLOB_BRACE);
 
//print each file name
foreach($images as $image)
{
echo "<a href=\"www.google.com\" title=\"image\"><img src=\"$image\" alt=\"Demo image\"></a>";
}

Now I am trying to do the same to fill in a different link for each image based on what the user put on the text file. So I did the following:

PHP:
//path to directory to scan
$directory = "photos/";
 
//get all image files with a .jpg extension.
$images = glob("" . $directory . "{*.jpg,*.gif,*.png}", GLOB_BRACE);

$fp = file('links.txt'); 
//print each file name
foreach($images as $image)
{
foreach($fp as $link) {
echo "<a href=\"$link\" title=\"image\"><img src=\"$image\" alt=\"Demo image\"></a>";
}
}


It worked except the images begin to repeat themselves, can anyone show me the right way to have two foreach statements grabbing information from two different sources but displaying all on one output?
 
It would be great if foreach loops could accept more than one value but they can't. The easiest solution around your problem is below.

PHP:
$fp = file('links.txt');
$num = count($fp) - 1;
$i = 0;
foreach($images as $image)
{
echo "<a href=\"{$fp[$i]}\" title=\"image\"><img src=\"$image\" alt=\"Demo image\"></a>";
if ($i < $num){$i++;}
else {break;}
} 
}

Now if you know that the amount of images is equal to the amount of links then you can omit the check to see if $i is less than $num. If you have any questions just ask.
 
Thank you for the reply! Your time is much appreciated. I have a few questions. Would you know what the method you implemented is called? Also, is there away where all images can display regardless of how many links there are, for example, if I have 3 links in the links.txt file, the first three images would reflect the first 3 links and the rest of the images would reflect no link or a generic link.
 
Of course that's very doable. Most of the code is already there for you. You only need to modify it a little.

PHP:
$fp = file('links.txt'); 
$num = count($fp) - 1; 
$i = 0; 
foreach($images as $image) 
{  
if ($i < $num) {
echo "<a href=\"{$fp[$i]}\" title=\"image\"><img src=\"$image\" alt=\"Demo image\"></a>";
$i++;
} 
else {
echo "<a href=\"generic-link.html\" title=\"image\"><img src=\"$image\" alt=\"Demo image\"></a>";}
}  
}

As for what the method I used is called it doesn't really have a name. I'm simply counting how many links are in the array and subtracting 1 because array indicators start at 0.
 
Status
Not open for further replies.
Back
Top Bottom