[solved]Array elements created twice

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
trdesigns
Forum Newbie
Posts: 9
Joined: Wed Aug 03, 2005 11:36 am
Location: Canada

[solved]Array elements created twice

Post 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?
Last edited by trdesigns on Wed Aug 03, 2005 12:30 pm, edited 1 time in total.
timvw
DevNet Master
Posts: 4897
Joined: Mon Jan 19, 2004 11:11 pm
Location: Leuven, Belgium

Post 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
josh
DevNet Master
Posts: 4872
Joined: Wed Feb 11, 2004 3:23 pm
Location: Palm beach, Florida

Post 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.
trdesigns
Forum Newbie
Posts: 9
Joined: Wed Aug 03, 2005 11:36 am
Location: Canada

Post 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
Post Reply