Associative array returnin number of key not name

Everywhere I have looked the code below should return:

Key=Bean, Value=Ben
Key=Calabrese, Value=Cal
Key=Carrot, Value=Car
Key=Chilli, Value=Chi
Key=Empty, Value=mty
Key=Tomato, Value=tom

But I am getting:
Key=0, Value=Ben
Key=1, Value=Cal
Key=2, Value=Car
Key=3, Value=Chi
Key=4, Value=mty
Key=5, Value=tom

$vegatable = array("Empty"=>"mty", "Tomato"=>"tom", "Bean"=>"Ben", "Chilli"=>"Chi", "Calabrese"=>"Cal", "Carrot"=>"Car");

sort($vegatable);

foreach ($vegatable as $x => $x_value) 
	{
		echo "Key=" . $x . ", Value=" . $x_value;
		echo "<br />";
	}

Please can somebody explain why - I am tying to create a dropdown list using the array.

A little bit down the page
http://php.net/manual/en/function.sort.php

Note : This function assigns new keys to the elements in array . It will remove any existing keys that may have been assigned, rather than just reordering the keys.

Thanks @Mittineague that is the problem - I did not think it would be a sort problem

I suppose I will have to make sure I create the array in the correct order.

Not necessarily, you could try one of the sort functions that maintains key associations
http://php.net/manual/en/array.sorting.php

Good point; ksort looks like it should work.

This is useful mainly for associative arrays.

Try this:

https://secure.php.net/manual/en/function.asort.php

Ninjaaaad :frowning:

1 Like

I would have guessed you wanted asort ^ maybe with a sort_flag. But if after looking at the examples and giving it a try you get the results you want, sure, sorting by keys could work.

1 Like

I went with asort to start with and that sorts by the value. The value and key are going to start with the same letter but after that I may need to use a different letter depending on how many options I have. So the key would probably be the best bet but I will see how it goes.

2 Likes

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.