You are here: Re: foreach loops are sooooo tricky..... « PHP Programming Language « IT news, forums, messages
Re: foreach loops are sooooo tricky.....

Posted by Jerry Stuckle on 12/02/07 12:47

Osiris wrote:
> On Sat, 01 Dec 2007 09:36:47 -0500, Jerry Stuckle wrote:
>
>> Osiris wrote:
>>> Just something I would like to share:
>>>
>>> I just learned the hard way (2 days detective work on a bug) that foreach
>>> loops are not at all like for loops, not intuitive at all. BEWARE: arrays
>>> and matrices are sparse by design/definition in PHP.
>>>
>>> I'm doing some matrix manipulation in a Finite Element program.
>>> Translating Fortran to PHP, because hosters won't allow anything else
>>> than PHP.
>>> I wish PHP would do array and matrix stuff like Fortran or C, btw.
>>> Something for PHP 6 ?
>>> Check out this code:
>>>
>>> $k = array(1=>
>>> array(1=>1,1,1,1,1,1),
>>> array(2=>1,1,1,1,1),
>>> array(3=>1,1,1,1),
>>> array(4=>1,1,1),
>>> array(5=>1,1),
>>> array(6=>1));
>>>
>>> /*
>
>> I find foreach loops to be quite intuitive. However, your FORTRAN
>> naming conventions make your code very hard to understand, and I don't
>> have the time to try to figure out what you're trying to do.
>>
>> Try using some descriptive names for your variables. It will make your
>> code a lot easier to understand.
>>
>
> There is nothing to describe , really... this example is just about a
> general matrix with numbers to be mirrored.
>
> The issue here is, that in a foreach loop you can inadvertedly enter extra
> coefficients in the matrix, that are processed in a next iteration.
> A for loop determins exactly which coefficients to process. A foreach loop
> processes all that it encounters, new or old.
> Mind you: I know what the problem is with the code. I did not say PHP was
> in error, just that foreach-es are not alway what you EXPECT them to
> be.

Well, a foreach loop is supposed to go through all of the elements. So
I would expect it to also process additional elements if you add them in
the loop.

However, if you add extra elements to an array, the for loop will also
process them, i.e.

$myArray[0] = 0;
for ($i=0; $i<count($myArray); $i++) {
$myArray[$i+1] = $i*2+2;
}

will run for a long time...

--
==================
Remove the "x" from my email address
Jerry Stuckle
JDS Computer Training Corp.
jstucklex@attglobal.net
==================

 

Navigation:

[Reply to this message]


Удаленная работа для программистов  •  Как заработать на Google AdSense  •  England, UK  •  статьи на английском  •  PHP MySQL CMS Apache Oscommerce  •  Online Business Knowledge Base  •  DVD MP3 AVI MP4 players codecs conversion help
Home  •  Search  •  Site Map  •  Set as Homepage  •  Add to Favourites

Copyright © 2005-2006 Powered by Custom PHP Programming

Сайт изготовлен в Студии Валентина Петручека
изготовление и поддержка веб-сайтов, разработка программного обеспечения, поисковая оптимизация