[FX.php List] foreach vs. first item in array

DC dan.cynosure at dbmscan.com
Tue Dec 13 20:56:09 MST 2005


Sorry, Dale, if this bothers you, but I love optimizing!

PHP is like any deep scripting language in that you can do things in a 
multitude of ways.

This replaces the key manipulations is the original function with the 
single current() function.

function getFirstRec($data)
	{
	return current($data);
	}

The current function always has the value of the first array element 
unless the array has been iterated over. Usually, current() is seen in 
the midst of array iterations that are programmed by hand for some 
reason or another, but in this case, current() is the fastest way to 
get to the first record of an array where the keys are unknown.

Even slimmer - lose the function:

$myFirstRec =current($returnedResult['data']);

HTH,
dan

On Dec 13, 2005, at 9:47 PM, Dale Bengston wrote:

> Hi Chuck,
>
> The array keys of $returnedResult['data'] are recid.modid for each 
> record, not self-assigned array keys (0, 1, 2 ...). That makes it 
> harder to pull the nth record without already knowing what its key is.
>
> I wrote a simple function to return the field data of the first record 
> in the found set, and I just use that. It could easily be adapted to 
> pull the last record or whatever record you need by sequential 
> index...
>
>
> $myFirstRec = getFirstRec($returnedResult['data']);
>
>
> function getFirstRec($data)
> 	{
> 	$resultKeys = array_keys($data);
> 	$firstKey = $resultKeys[0];
> 	$firstRec = $data[$firstKey];
> 	
> 	return $firstRec;
> 	}
>
>
> Hope this helps,
> Dale
>
> --
> Dale Bengston | Streamline Studio, LLC | 
> dbengston at streamline-studio.com
> Associate Member, FileMaker Solutions Alliance
>
>
>
>
>
> On Dec 13, 2005, at 4:36 PM, Charles Ross wrote:
>
>> Both in the FX.php in 8 Hours book and here on this mailing list, 
>> I've seen this line of code to extract a single item from the object 
>> returned with an FMFind():
>>
>> foreach($returnedResult['data'] as $key => $value);
>>
>> From what I understand, this is useful when there should be a single 
>> record returned in $returnedResult. If that's the case, why not use:
>>
>> $value = $returnedResult['data'][0];
>>
>> Is there an advantage to using the foreach rather than the array 
>> index version? I did some testing, and it seemed to work the same, 
>> and the latter one seems easier to read and more straightforward, so 
>> I'm wondering if I'm missing something.
>>
>> Thanks,
>> Chuck Ross
>> _______________________________________________
>> FX.php_List mailing list
>> FX.php_List at mail.iviking.org
>> http://www.iviking.org/mailman/listinfo/fx.php_list
>
>
>
> _______________________________________________
> FX.php_List mailing list
> FX.php_List at mail.iviking.org
> http://www.iviking.org/mailman/listinfo/fx.php_list
>



More information about the FX.php_List mailing list