cmccarra
cmccarra

Reputation: 199

Limiting a foreach loop to the first array

here is my code:

<?php
         foreach ($productsRecord['images'] as $upload):?>
          <?php if ($upload['hasThumbnail']): ?>
            <a href="<?php echo $upload['urlPath'] ?>" rel="lightbox" class="imgborder" title="<?php echo $productsRecord['name'] ?>"><img src="<?php echo $upload['urlPath'] ?>"  alt="" /></a><br />



          <?php endif ?>
        <?php endforeach ?>

How would I go about limiting the results to only the first result, would I use a break; statement?

Cheers

Upvotes: 2

Views: 286

Answers (3)

Sena
Sena

Reputation: 914

Try to use current()

your code shall like that:

<?php reset($productsRecord['images']); ?>
<?php $upload = current($productsRecord['images']);?>
<?php if ($upload['hasThumbnail']): ?>
    <a href="<?php echo $upload['urlPath'] ?>" rel="lightbox" class="imgborder" title="<?php echo $productsRecord['name'] ?>"><img src="<?php echo $upload['urlPath'] ?>"  alt="" /></a><br />
<?php endif ?>

To more information about the current() check the manual: http://php.net/manual/en/function.current.php

Upvotes: 2

Sherlock
Sherlock

Reputation: 7597

Just use the first element of the array directly

$productsRecord['images'][0]

No need to loop here.

Upvotes: 2

dynamic
dynamic

Reputation: 48091

Yes, use break

    <?php break; endforeach; ?>

Upvotes: 1

Related Questions