Jjames
Jjames

Reputation: 183

Proper PHP syntax for cycleing through an array with the index

I am newish to PHP and I am trying to cycle through an array and stop after 5 items. I am using the following:

    $images = ( $f->APIVer == "1.2.2" ) ? $images['Images'] : $images;
            // Display the thumbnails and link to the medium image for each image
            foreach ( $images as $index => $image) {

                echo '<li><a href="'.$image['XLargeURL'].'"><img src="'.$image['TinyURL'].'" alt="thumbnail"/></li>';
            }
            while ( $index < 5 );
        }

Although it does not seem to work... Am I doing something wrong?

Thanks in advance

Upvotes: 0

Views: 93

Answers (4)

JK.
JK.

Reputation: 5136

Given that $index is an integer you could just break out of the loop:

foreach ($images as $index => $image) {
    echo '<li><a href="'.$image['XLargeURL'].'"><img src="'.$image['TinyURL'].'" alt="thumbnail"/></li>';
    if ($index >= 5) {
        break;
    }
}

Upvotes: 0

PeeHaa
PeeHaa

Reputation: 72682

If the array has a zero based index you can do:

foreach ( $images as $index => $image) {
    if ($index == 5) break;
    echo '<li><a href="'.$image['XLargeURL'].'"><img src="'.$image['TinyURL'].'" alt="thumbnail"/></li>';
}

Otherwise you can add your own counter:

$i = 0;
foreach ( $images as $index => $image) {
    $i++;
    if ($i == 5) break;
    echo '<li><a href="'.$image['XLargeURL'].'"><img src="'.$image['TinyURL'].'" alt="thumbnail"/></li>';
}

What you tried is another type of loop:

$index = 0;
do {
    echo '<li><a href="'.$images[$index]['XLargeURL'].'"><img src="'.$images[$index]['TinyURL'].'" alt="thumbnail"/></li>';
    $index++;
} while ( $index < 5 );

Or:

$index = 0;
while ( $index < 5 ) {
    echo '<li><a href="'.$images[$index]['XLargeURL'].'"><img src="'.$images[$index]['TinyURL'].'" alt="thumbnail"/></li>';
    $index++;
}

Another alternative would be a for loop:

for($index=0; $index < 5; $index++) {
    echo '<li><a href="'.$images[$index]['XLargeURL'].'"><img src="'.$images[$index]['TinyURL'].'" alt="thumbnail"/></li>';
}

Upvotes: 4

Jeroen
Jeroen

Reputation: 13257

It should be like this:

$images = ( $f->APIVer == "1.2.2" ) ? $images['Images'] : $images;

$i = 0;
// Display the thumbnails and link to the medium image for each image
foreach ( $images as $index => $image) {
    if ($i == 5) break;
    echo '<li><a href="'.$image['XLargeURL'].'"><img src="'.$image['TinyURL'].'" alt="thumbnail"/></li>';
    $i++;
}

while is a loop on its own, just like foreach.

Upvotes: 0

mgraph
mgraph

Reputation: 15338

   $images = ( $f->APIVer == "1.2.2" ) ? $images['Images'] : $images;
   $nm = 0;
   foreach ( $images as $index => $image) {
      if($nm < 5){
           echo '<li><a href="'.$image['XLargeURL'].'"><img src="'.$image['TinyURL'].'" alt="thumbnail"/></li>';
         }
       $nm++;
       }

Upvotes: 0

Related Questions