|
Posted by Osiris on 12/01/07 14:20
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>";
}
[Back to original message]
|