cpdavngr Posted August 27, 2007 Share Posted August 27, 2007 I'm relatively new to PHP, but not to programming in general. Anyway, I had a question about associative arrays. Take a look at the following example: Why does the following code: echo "\n*************declared***************************\n"; $tester=array("bob"); $tester["bob"]=65433; foreach ($tester as $value) echo "$value\n"; echo "\n"; print_r($tester); echo "\n**********undeclared****************************\n"; unset($tester); /*$tester=array("bob");*/ $tester["bob"]=65433; foreach ($tester as $value) echo "$value\n"; echo "\n"; print_r($tester); Produce this output: *************declared*************************** bob 65433 Array ( [0] => bob [bob] => 65433 ) **********undeclared**************************** 65433 Array ( [bob] => 65433 ) Shouldn't bob have a numerical index in the array either declared or undeclared? This is somewhat confusing because I'm trying to use a foreach loop to loop through a predeclared associative array and I'm getting multiple results in my output... Quote Link to comment Share on other sites More sharing options...
Wuhtzu Posted August 27, 2007 Share Posted August 27, 2007 First of all why have you commented out the $tester=array("bob");? If I uncomment the line above and run the script i get this: *************declared*************************** bob 65433 Array ( [0] => bob [bob] => 65433 ) **********undeclared**************************** bob 65433 Array ( [0] => bob [bob] => 65433 ) And that is how it should be... $tester = array('bob') assigns the comma separated values an numeric index starting at 0... so $tester[0] holds the value 'bob'. That's perfectly as it should be... I don't know why you get that odd sign instead of [0]. Quote Link to comment Share on other sites More sharing options...
GingerRobot Posted August 27, 2007 Share Posted August 27, 2007 The output you get is exactly as you would expect. In your first set of code, you firstly create an array, with an element which is the string 'bob' in it. This has the key 0 - since you did not specify a key. You then add a new element to your array, which has the key 'bob' and value 65433. You therefore have two elements in you array - one of which has the value bob, whilst the key of the other is bob. In the second code sample, you only put the element with the key bob and the value 65433. Therefore, when you print out the contents, there is only one thing in your array. It's not an issue of declaration - in both cases you implicitly define your array by placing elements into it. It is simply a case of the number of elements you put into it. I hope that makes more sense than i think it might. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.