Aaron R
Aaron R

Reputation: 233

Php while loop exclude first of array

<div id="prettyphoto" align="left"> <a href="http://images.idealer1.com/getimage/999/<?php echo $image['vpid'] ?>.jpg" rel="prettyPhoto[gallery2]"><img src="http://images.idealer1.com/getimage/700/<?php echo $image['vpid'] ?>.jpg" width="100" alt="" /></a>
  <ul class="gallery clearfix">
    <?php foreach ($images as $image) { ?>
    <li><a href="http://images.idealer1.com/getimage/999/<?php echo $image['vpid'] ?>.jpg" rel="prettyPhoto[gallery2]"><img src="http://images.idealer1.com/getimage/100/<?php echo $image['vpid'] ?>.jpg" width="100" alt="" /></a></li>
    <? } ?>
  </ul>
</div>

I am trying to take this foreach loop of thumbnails and exclude the first image and have it load as a larger image I can't seem to figure out the proper way to accomplish this.

Upvotes: 0

Views: 2122

Answers (3)

Flavius
Flavius

Reputation: 13816

You can iterate the array "manually", with next(), current(), etc:

<?php
$images = array(
    array('vpid' => 1, ),
    array('vpid' => 2, ),
    array('vpid' => 3, ),
    array('vpid' => 4, ),
);

$image = current($images);
?>
<div id="prettyphoto" align="left"> <a href="http://images.idealer1.com/getimage/999/<?php echo $image['vpid'] ?>.jpg" rel="prettyPhoto[gallery2]"><img src="http://images.idealer1.com/getimage/700/<?php echo $image['vpid'] ?>.jpg" width="100" alt="" /></a>
  <ul class="gallery clearfix">
    <?php
    next($images);
    while(list($idx, $image) = each($images)) { ?>
    <li><a href="http://images.idealer1.com/getimage/999/<?php echo $image['vpid'] ?>.jpg" rel="prettyPhoto[gallery2]"><img src="http://images.idealer1.com/getimage/100/<?php echo $image['vpid'] ?>.jpg" width="100" alt="" /></a></li>
    <? } ?>
  </ul>
</div>

Read: http://www.php.net/manual/en/function.each.php

With array_shift() you could "loose" the first image (you have to put it back in after you're done).

With array_slice() you would duplicate data, which is bad practice in general.

Upvotes: 1

Felix Kling
Felix Kling

Reputation: 816364

You could use array_shift():

<?php $firstImage = array_shift($images); ?>
<!-- do something with $firstImage -->
<?php foreach ($images as $image): ?>
    ...
<?php endforeach; ?>

or if you don't need a reference to the first image, array_slice():

<?php foreach(array_slice($images, 1) as $image): ?>
    ...
<?php endforeach; ?>

Also note the use of the alternative syntax for control structures which makes reading the mixture of PHP and HTML a bit easier (but is not related to your problem).

Upvotes: 4

Sujit Agarwal
Sujit Agarwal

Reputation: 12508

you can use some idea from this:

foreach($array as $key=>$value)
{
    if($key==0)
    echo "code for the large image";
    else
    echo "code for the thumbnail image";
}

Upvotes: 0

Related Questions