0

Array:

$cities = array("Paris" => "10", "Amsterdam" => '20', "California" => '30', "Barcelona" => "70");

Sort:

asort($cities);

print_r:

print_r (array_keys($cities));

Results:

Array ( [0] => Paris [1] => Amsterdam [2] => California [3] => Barcelona )

I want to return the city who has the key 2. (It should be California)

UPDATE

I solved it like this (Thanks to ArSeN):

$array1 = array_keys($cities);
$city = $array1[2];
Sara Z
  • 625
  • 7
  • 18
  • 2
    `var_dump($array[2])`? – u_mulder Jan 21 '16 at 15:52
  • 3
    Are you sure you want to know which city has the key 2? Or do you mean you want to know which key in the array has the value "California"? – ArSeN Jan 21 '16 at 15:52
  • @ArSeN Yes. Because I have already the key (Ranking) and I want to now which user has this key. – Sara Z Jan 21 '16 at 15:56
  • Then the response from u_mulder is already what you are looking for. Just access the array entry with the specified key like this: `$array[2]`. If you feel that this helped you, you should probably close the question, as this is very basic understanding of how arrays work. – ArSeN Jan 21 '16 at 15:58

1 Answers1

0
$city = array_keys($array1)[2];

Stores "California" in $city.

  • IIRC older PHP versions don't support it like this. You might want to store the result of array_keys in a variable first and get your index afterwards. $tmp = array_keys($array1); $city = $tmp[2]; – COMMANDER CAPSLOCK Jan 21 '16 at 16:16
  • See [this post](http://stackoverflow.com/a/10482105/2979155) - it's supported since version 5.4 – COMMANDER CAPSLOCK Jan 21 '16 at 16:23