PHP - Exit function prematurely

Introduction

You can break out of a loop is that you want to exit the loop prematurely.

Consider the following example:

Demo

<?php

         $randomNumber = rand( 1, 1000 );

         for ( $i=1; $i  <= 1000; $i++ ) {
           if ( $i == $randomNumber ) {
             echo "Hooray! I guessed the random number. It was: $i \n ";
             break;
           }/*from   w w  w . j a  va 2 s. c  o m*/
         }
?>

Result

This code uses PHP's rand() function to generate and store a random integer between 1 and 1000.

Then loops from 1 to 1000, trying to guess the previously stored number.

Once it's found the number, it displays a success message and exits the loop with break.

If you omit the break statement and the code would still work.

But there's no point in continuing once the number has been guessed.

Using break to exit the loop avoids wasting processor time.

Related Topic