[FX.php List] A nagging question: Foreach

Bob Patin bob at patin.com
Mon Sep 22 16:56:05 MDT 2008


Jonathan,

You can use this:

foreach($findResult['data'] as $key => $value);

Notice the semicolon...

followed by a list of fields that you're retrieving from $value...

Or you can use a loop to get a set of records:

foreach($findResult['data'] as $key => $value){
	$field1 = $value['field1'][0];
	$field2 = $value['field2'][0];
	$field3 = $value['field3'][0];
}

Leaving a blank line makes no difference; my preference is to put my  
curly brackets as I have above, because I think it shows the process  
better.

I painstakingly indent everything, so if I have an IF statement inside  
the FOREACH, I indent even further:

foreach($findResult['data'] as $key => $value){
	if ($red == $blue){
		echo "You are color-blind.";
	}
	$field1 = $value['field1'][0];
	$field2 = $value['field2'][0];
	$field3 = $value['field3'][0];
}

But PHP doesn't see all that pretty indenting and blank lines...

BP

Bob Patin
Longterm Solutions
bob at longtermsolutions.com
615-333-6858
http://www.longtermsolutions.com
iChat: bobpatin
AIM: longterm1954
FileMaker 9 Certified Developer
Member of FileMaker Business Alliance and FileMaker TechNet
--------------------------
FileMaker hosting and consulting for all versions of FileMaker
PHP • Full email services • Free DNS hosting • Colocation • Consulting


On Sep 22, 2008, at 5:48 PM, Jonathan Schwartz wrote:

>
> A long term nagging question:
>
> Foreach syntax after an Instance
> After an instance of FMPFind, FMNew, FMEdit, etc, we all use the  
> standard foreach statement to retrieve values from a single record  
> that was just created, edited, etc. Sometime, I leave the foreach  
> statement in the same place and retrieve the values later in the  
> script.  When using the foreach statement in this second case, I  
> find that I have to leave an empty line after the foreach.   
> Otherwise, things go wrong.
>
>
> THIS IS FINE:
> $findResult = $query->FMFind();
> foreach($findResult['data'] as $key => $value)
> $retrievedvalue = $value['retrievedvalue'][0];
>
> THIS ISN'T:
> $findResult = $query->FMFind();
> foreach($findResult['data'] as $key => $value)
> (SOME OTHER STATEMENTS); <---this goes wrong.
> $retrievedvalue = $value['retrievedvalue'][0];
>
> Is it implied that the line directly following a foreach statement  
> acts on the line following it?
>
> Is the proper syntax to either leave an empty line, of perhaps empty  
> brackets after the foreach?:
>
> IS THIS BETTER?:
> $findResult = $query->FMFind();
> foreach($findResult['data'] as $key => $value)
> {}
> (SOME OTHER STATEMENTS);
> $retrievedvalue = $value['retrievedvalue'][0];
>
>
> Jonathan



More information about the FX.php_List mailing list