- PHP

How to exit Foreach Loop in PHP

We may want to end the foreach loop when it meets a certain condition.

To do this, we can use break.

<?php

foreach($array as $value) {
    // your code

    break;
}

?>

Example:

End a foreach array when the if the condition returns true.

<?php

$array = ['red', 'green', 'blue', 'purple', 'cyan', 'magenta'];

foreach($array as $value) {
    echo $value . '<br>';

    if($value == 'blue') {
        break;
    }
}

?>

Output:

red
green
blue