note 96591 added to control-structures.while

From: Date: Sat, 06 Mar 2010 15:34:26 +0000
Subject: note 96591 added to control-structures.while
Groups: php.notes 
Request: Send a blank email to php-notes+get-166735@lists.php.net to get a copy of this message
I find it often clearer to set a simple flag ($finished) to false at the start of the loop, and have the program set it to true when it's finished doing whatever it's trying to do. Then the code is more self-documenting: WHILE NOT FINISHED keep going through the loop. FINISHED EQUALS TRUE when you're done. Here's an example. This is the code I use to generate a random filename and ensure that there is not already an existing file with the same name. I've added very verbose comments to it to make it clear how it works: <?php $finaldir = 'download'; $finished = false; // we're not finished yet (we just started) while ( ! $finished ): // while not finished $rn = rand(); // random number $outfile = $finaldir.'/'.$rn.'.gif'; // output file name if ( ! file_exists($outfile) ): // if file DOES NOT exist... $finished = true; // ...we are finished endif; endwhile; // (if not finished, re-start WHILE loop) ?> ---- Server IP: 64.71.164.2 Probable Submitter: 67.165.168.203 ---- Manual Page -- http://www.php.net/manual/en/control-structures.while.php Edit -- https://master.php.net/note/edit/96591 Del: integrated -- https://master.php.net/note/delete/96591/integrated Del: useless -- https://master.php.net/note/delete/96591/useless Del: bad code -- https://master.php.net/note/delete/96591/bad+code Del: spam -- https://master.php.net/note/delete/96591/spam Del: non-english -- https://master.php.net/note/delete/96591/non-english Del: in docs -- https://master.php.net/note/delete/96591/in+docs Del: other reasons-- https://master.php.net/note/delete/96591 Reject -- https://master.php.net/note/reject/96591 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#166735) next »