Problem:
I have a foreach loop that works great for pulling images but when I try to replace it with a for loop it breaks the code and images.
PHP code:
// Create counter
$i = 0;
// Set number of photos to show
$count = 5;
// Set height and width for photos
$size = '100';
// Show results
foreach ($media->data as $data)
{
// Show photo
echo '<p><img src="'.$data->images->thumbnail->url.'" height="'.$size.'" width="'.$size.'" alt="Instagram bild"></p>';
// Abort when number of photos has been reached
if (++$i == $count) break;
}
Desired solution:
To replace foreach with for and set counter in the for loop instead. This is probably really easy but for some reason I am completely stuck right now.
This is if your
$media->datavariable could be indexed.If not you have to use
foreachbut notforand exit from the loop when you reach the needed number of photos:Also as it was written in the comments below it is a good idea to check the size of your
$media->datavariable if there are less than 5 images. You can make something like: