List Info

Thread: note 78512 added to control-structures.foreach




note 78512 added to control-structures.foreach
user name
2007-10-15 16:44:33
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.forea
ch.php
Edit        -- https://master
.php.net/note/edit/78512
Del: integrated  -- h
ttps://master.php.net/note/delete/78512/integrated
Del: useless     -- http
s://master.php.net/note/delete/78512/useless
Del: bad code    -- htt
ps://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     -- http
s://master.php.net/note/delete/78512/in+docs
Del: other reasons-- https://mast
er.php.net/note/delete/78512
Reject      -- https://mast
er.php.net/note/reject/78512
Search      -- https://
master.php.net/manage/user-notes.php

-- 
PHP Notes Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub
.php


note 78512 deleted from control-structures.foreach by nlopess
user name
2007-10-21 16:56:10
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.

-- 
PHP Notes Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub
.php


[1-2]

about | contact  Other archives ( Real Estate discussion Medical topics )