2

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

3
  • Can you elaborate it a bit more? Do you want just the first element of $productsRecord['images'] ? Commented Jun 18, 2012 at 12:47
  • Yes, I just want the first image to appear. Commented Jun 18, 2012 at 12:47
  • then just use the first element of the array directly.. Why do you even need to loop for just one element? Commented Jun 18, 2012 at 12:50

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

Or if you want to be absolutely sure that you get the first element, use reset instead of current
@user1463691 if worked as needed plz mark the answer as correct :)
2

Just use the first element of the array directly

$productsRecord['images'][0]

No need to loop here.

2 Comments

Just as a hint: On SO, you will want to indent code with four spaces so it is properly highlighted. If you want to include a variable or function name (or something else) within regular text, you can use inline highlighting by surrounding the code with backticks (`).
Also, as a good practice, you should always check if an index in an array exists before retrieving it. That way you avoid nasty undefined index warnings.
1

Yes, use break

    <?php break; endforeach; ?>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.