3
votes

I have an associative array, which keys I want to use in numbers. What I mean: The array is kinda like this:

$countries = array
    "AD"  =>  array("AND", "Andorra"),
    "BG"  =>  array("BGR", "Bulgaria")
);

Obviously AD is 0 and BG is 1, but when I print $countries[1] it doesn't display even "Array". When I print $countries[1][0] it also doesn't display anything. I have the number of the key, but I shouldn't use the associative key.

4
You want to use a string key and a numeric key. Why don't you do this with a SQL TABLE with a schema of id, code, name?Fabián Heredia Montiel
Maybe it's not so obvious that "AD is 0". Maybe it's not even true?Kerrek SB
fabianhjr: Yes and II cant use an SQL Table, because the script has a lot of modules and I'm not sure which uses which. KerrekSB: Why?user890450

4 Answers

20
votes

Perfect use case for array_values:

$countries = array_values($countries);

Then you can retrieve the values by their index:

$countries[0][0]; // "AND"
$countries[0][1]; // "Andorra"
$countries[1][0]; // "BGR"
$countries[1][1]; // "Bulgaria"
4
votes

array_keys() will give you the array's keys. array_values() will give you the array's values. Both will be indexed numerically.

1
votes

you might convert it into a numeric array:

    $countries = array(
    "AD"  =>  array("AND", "Andorra"),
    "BG"  =>  array("BGR", "Bulgaria")
);
$con=array();
$i=0;
foreach($countries as $key => $value){
    $con[$i]=$value;
    $i++;
}
echo $con[1][1];

//the result is Bulgaria
0
votes

There are a couple of workarounds to get what you want. Besides crafting a secondary key-map array, injecting references, or an ArrayAccess abomination that holds numeric and associative keys at the same time, you could also use this:

 print current(array_slice( current(array_slice($countries, 1)), 0));

That's the fugly workaround to $countries[1][0]. Note that array keys appear to appear in the same order still; bemusing.