|
Posted by Jerry Stuckle on 12/01/07 14:36
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));
>
> /*
> you would expect this to mirror the matrix about a diagonal from upper
> left to lower right multiplying each coefficient by 2 on the way...
> However, the foreach loop is tricky. */
> foreach($k as $i=>& $_k)
> foreach($_k as $j=>&$__k)
> {
> $__k *= 2;
> if ($i != $j)
> $k[$j][$i ] = $__k;
> }
>
> foreach($k as &$_k)
> {
> foreach($_k as &$__k)
> echo " $__k ";
> echo "<BR>";
> }
>
> echo "<BR>";
>
> /* this is better: */
>
> $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));
>
> for ($i=1; $i <= 6; $i++)
> for ($j=$i; $j<= 6; $j++)
> if (isset($k[$i][$j]))
> {
> $k[$i][$j] *= 2 ;
> if ($i != $j)
> $k[$j][$i] = $k[$i][$j];
> }
> foreach($k as &$_k)
> {
> foreach($_k as &$__k)
> echo " $__k ";
> echo "<BR>";
> }
> echo "<BR";
> /*
> * and what about this:
> *
> */
> $k = array(1=>
> array(1=>1,1,1,1,1,1),
> array(2=>1,6=>1),
> array(3=>1,1,1,1),
> array(4=>1,1,1),
> array(5=>1,1),
> array(6=>1));
>
> for ($i=1; $i <= 6; $i++)
> for ($j=$i; $j<= 6; $j++)
> if (isset($k[$i][$j]))
> {
> $k[$i][$j] *= 2 ;
> if ($i != $j)
> $k[$j][$i] = $k[$i][$j];
> }
> foreach($k as &$_k)
> {
> foreach($_k as &$__k)
> echo " $__k ";
> echo "<BR>";
> }
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.
--
==================
Remove the "x" from my email address
Jerry Stuckle
JDS Computer Training Corp.
jstucklex@attglobal.net
==================
[Back to original message]
|