|
Posted by Tim Roberts on 12/02/07 00:53
Osiris <et57@hotmail.com> 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.
That's true, but I don't think that's the problem here.
>I wish PHP would do array and matrix stuff like Fortran or C, btw.
>Something for PHP 6 ?
I doubt it. That's simply not its problem domain.
>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. */
My guess is that it's not the foreach loop that is biting you, but rather
the references.
>foreach($k as $i=>& $_k)
> foreach($_k as $j=>&$__k)
> {
> $__k *= 2;
> if ($i != $j)
> $k[$j][$i ] = $__k;
> }
What does this produce for you? Does the next-to-the-last line really do
what you think? Is that making a copy of the value, or is it storing a
reference to the value? That is, won't $k[2][1] simply be a reference to
$k[1][2], and not a separate value?
My only convenient server runs PHP 4, which does not support the reference
notation. If I change your code to this, which I believe to be equivalent:
foreach($k as $i=> $_k)
foreach($_k as $j=>$__k)
{
$__k *= 2;
$k[$i][$j] = $__k;
if ($i != $j)
$k[$j][$i ] = $__k;
}
the result is a 6x6 square array where every element is 2.
--
Tim Roberts, timr@probo.com
Providenza & Boekelheide, Inc.
Navigation:
[Reply to this message]
|