----- Original Message ----- 
From: "James Keeline"
> 
> --- Bob <[EMAIL PROTECTED]> wrote:
> 
>> Something I've always been meaning to ask.
>> If going thro a large amount of data, does it matter whether I compare the
>> value to the array item, or visa-versa?
>> 
>> $colr = array('red', 'blue', 'green', etc);
>> example 1
>> foreach($colr as $item) {
>>   if ($item == 'blue')
>>   // Do something
>> }
>> example 2
>> foreach($colr as $item) {
>>   if ('blue' == $item)
>>   // Do something
>> }
>> 
>> Obviously, example 1 is more readable. But I seem to remember reading that
>> one is more beneficial, but dismissed it at the time.
>> Thanks, Bob.
> 
> I have seen some suggest using the comparison you have in example 2 because 
> you
> will get a parse error if you try to use a single equal sign (assignment)
> instead of a double equal (comparison).  PHP will cheerfully take the first
> example and if you have a single equal sign it will make the assignment and 
> the
> resulting expression will be true (unless the value is 0).
> 
> Looping through an array for a value might be better served with 
> array_search()
> or array_keys() depending on whether you want/expect only one value or 
> multiple
> occurrences of the value in the search array.  For an array with a dozen or 
> 100
> items it probably doesn't make a noticeable difference but larger arrays could
> benefit from using the optimized functions for this purpose.

Hi James,
It was a hypothetical question really and not something I'm using.
So reading between the lines, use whichever is more readable when comparing 
values.
I'd got from somewhere that one was better on resources that the other, but it 
probably was ficticious.
Thanks, Bob.


Reply via email to