5

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.

3
  • 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? Commented Jan 8, 2012 at 23:33
  • 1
    Maybe it's not so obvious that "AD is 0". Maybe it's not even true? Commented Jan 8, 2012 at 23:33
  • 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? Commented Jan 8, 2012 at 23:54

4 Answers 4

22

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"
Sign up to request clarification or add additional context in comments.

Comments

5

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

Comments

0

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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.