0

I searched up similar questions, but none of those gave me answers I'm looking for.

Here's the script:

        <?php foreach ($images as $key => $image) {
            if (isset($_GET['locations']) && $_GET['locations'] == $key) {?>
                <img src="images/<?= $_GET['locations']; ?>" alt="" width=500px height=300>
                <figcaption><?= $image; ?></figcaption>
            <?php }
        } ?>

I'm trying to break out of the foreach loop once the images clicked matches the condition of my if statement, how can I do that?

Irshu
  • 8,248
  • 8
  • 53
  • 65
Gnahzllib
  • 91
  • 1
  • 12

1 Answers1

1

Inside your if case, simply add a break. If you need more information about break, you can read the PHP Documentation.

<?php foreach ($images as $key => $image) {
    if (isset($_GET['locations']) && $_GET['locations'] == $key) {?>
        <img src="images/<?= $_GET['locations']; ?>" alt="" width=500px height=300>
        <figcaption><?= $image; ?></figcaption>
        <?php break; ?>
    <?php }
} ?>
Chin Leung
  • 14,621
  • 3
  • 34
  • 58
  • Hi Chin, I just read an article that said adding a break inside the if statement is a bad idea.http://stackoverflow.com/questions/24714287/break-out-of-if-statement – Gnahzllib May 08 '16 at 01:52
  • It's not saying it's bad to have a break inside the if statement. It just says you have to be careful to know what you're "breaking" out of. – Chin Leung May 08 '16 at 02:00