note 78512 deleted from control-structures.foreach by nlopess

From: Date: Sun, 21 Oct 2007 21:56:10 +0000
Subject: note 78512 deleted from control-structures.foreach by nlopess
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-131602@lists.php.net to get a copy of this message
Note Submitter: petruzanauticoyahoo?com!ar ---- For that cases you want to do something inside a loop BUT omit it the frist time, I've came up with this construct. ( for example you want to build this query: "SELECT id, name, surname, email, phone FROM ..." you have the fields in an array, and you don't wanna put a comma before the first field, nor after the last one. ) <?php $first_time = true; foreach( $fields as $field ) { if( !$first_time ) // every loop BUT the first, add a comma $query .= ", "; else $first_time = false; // stop adding commas $query .= $field; [...] } ?> Notice that the check is not for ( $first_time ) but for ( !$first_time ), because this condition will be true most of the time, so *I think* it is a little faster for avoiding jumping to the else clause.

« previous php.notes (#131602) next »