Page 1 of 1

[solved]Array elements created twice

Posted: Wed Aug 03, 2005 11:44 am
by trdesigns
Hi, I'm having a little trouble understanding why the following code:

Code: Select all

$foo=array("a" => 1, "b" => 2, "c" => 3);

foreach($foo as $key => $value)
{
echo "{$key} - {$value} <br>";
}
Outputs:

Code: Select all

a - 1
b - 2
c - 3
0 - 1
1 - 2
2 - 3
And if I change one of the elements and output:

Code: Select all

$foo['a']=5;

foreach($foo as $key => $value)
{
echo "{$key} - {$value} <br>";
}
I get:

Code: Select all

a - 5
b - 2
c - 3
0 - 1
1 - 2
2 - 3
Is this the correct behaviour or am I doing something wrong? Should the numerical and string indexes be independent of each other?

Posted: Wed Aug 03, 2005 11:56 am
by timvw
Which is the PHP version you are using? I'm experiencing similar oddities with FreeBSD/PHP4.4 (viewtopic.php?t=36184&highlight=array+php4)


Your output should be:
a - 1
b - 2
c - 3

and:
a - 5
b - 2
c - 3

Posted: Wed Aug 03, 2005 12:07 pm
by josh
Yeah that is weird, print_r() the array and post your output, so we we can tell if its the array itself that's getting fubar'd or if it's the foreach construct that's causing the bug.

Posted: Wed Aug 03, 2005 12:27 pm
by trdesigns
Nevermind, I think I figured out my problem. It was related to the mysql_fetch_assoc() function that I was using. It returns both associative and numerical indexes and I forgot to eliminate the numerical portion of that array.

Sorry for the false alarm :oops: and for the record I'm also using PHP 4.4