Gnahzllib Gnahzllib - 7 months ago 11
PHP Question

How to breaking out of a loop if a condition is valid in PHP?

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?

Answer

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 }
} ?>