How do you exit or break out of a running loop before it has finished completing in PHP?
Well luckily PHP makes it pretty easy by providing us with the break control structure, a function that forces the ending of the execution of the current for, foreach, while, do-while, or switch structure.
You can extend break‘s range by utilizing its single numeric argument that tells it how many nested enclosing structures need to in fact be broken out of.
In other words, a bloody useful function to know! :)
Example Usage:
while(true) { echo date('Y/m/d H:i:s') . '
'; break; }
The code above launches an infinite continuing loop that will print out the current time until the application is eventually forced closed. However, by inserting the break command, the date only gets echoed out once before the loop is forcefully terminated.
If this while loop had been contained within another while loop, the code as it stands would simply break out of the first while loop but continue to execute as part of the top while loop – however, if we specify break 2, the application would forcefully exit both while loops and thus finish execution.
Related Link: http://php.net/manual/en/control-structures.break.php
You might also enjoy:
-
By now, you'll know that loops are essential to your livelihood as a programmer and as such you have lovingly nurtured your loops, nesting and expanding the ...
-
I stumbled across this gem of a quick guide to Bash shell scripting over at some or other forum and so as not to lose this valuable resource for my later us ...
-
More often than not, your HTML elements will have more than one class assigned to them. Now while it is easy to check if an element belongs to a certain cla ...
-
Sometimes you wish to apply a certain function, be it a built in PHP function or one of your own creations, to each and every value within a particular arra ...
-
To loop through all the string inputs entered on a new line for a textarea control is not particularly challenging and uses basic array functionality to ach ...