note 78512 added to control-structures.foreach
| From: | petruzanauticoyahoo?com!ar at osu1 dot php dot net | Date: | Mon, 15 Oct 2007 21:44:33 +0000 |
| Subject: | note 78512 added to control-structures.foreach | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-131410@lists.php.net to get a copy of this message | ||
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.
----
Server IP: 190.2.55.3
Probable Submitter: 24.232.22.244
----
Manual Page -- http://www.php.net/manual/en/control-structures.foreach.php
Edit -- https://master.php.net/note/edit/78512
Del: integrated -- https://master.php.net/note/delete/78512/integrated
Del: useless -- https://master.php.net/note/delete/78512/useless
Del: bad code -- https://master.php.net/note/delete/78512/bad+code
Del: spam -- https://master.php.net/note/delete/78512/spam
Del: non-english -- https://master.php.net/note/delete/78512/non-english
Del: in docs -- https://master.php.net/note/delete/78512/in+docs
Del: other reasons-- https://master.php.net/note/delete/78512
Reject -- https://master.php.net/note/reject/78512
Search -- https://master.php.net/manage/user-notes.php