0

I have a two dimensional array. I'm trying to get the key/index name of a given value. How do I do this? I went through the PHP manual and they suggest to do an iteration, but I do not want to iterate. Is there a way to do without iteration?

I would like to do something similar to

$country = 'Algeria';
echo $iso_countries[$country]; //obviously this will throw an error since the index does not exist. It's just an example.

array

$iso_countries = array
(
    'AF' => 'Afghanistan',
    'AX' => 'Aland Islands',
    'AL' => 'Albania',
    'DZ' => 'Algeria',
);
2
  • If the array is sorted by value you can do a binary search which will find any entry in a list of 256 or fewer entries in at most 8 steps. Other than that, you'd need to pre-build an index that maps country names to their abbreviations, which is essentially what array_flip() will do. Commented Apr 28, 2020 at 1:17
  • You should also disabuse yourself of the notion that "loops are bad". Loops are fundamental to doing virtually everything and you should instead invest your effort in learning when/why loops can be used badly and avoid those, rather than trying to engineer around a non-existent problem. Commented Apr 28, 2020 at 1:23

2 Answers 2

2

You should use array_search

$iso_countries = array
(
    'AF' => 'Afghanistan',
    'AX' => 'Aland Islands',
    'AL' => 'Albania',
    'DZ' => 'Algeria',
);

$founded = array_search('Algeria',$iso_countries);
echo $founded;
Sign up to request clarification or add additional context in comments.

Comments

2

No there is no way to get the key of value from an array without an explicit (foreach,while,for) or implicit (in_array,array_flip,array_search) iteration.

PHP ARRAY MANUAL: An array in PHP is actually an ordered map. A map is a type that associates values to keys. This type is optimized for several different uses; it can be treated as an array, list (vector), hash table (an implementation of a map), dictionary, collection, stack, queue, and probably more. As array values can be other arrays, trees and multidimensional arrays are also possible.

From the doc, array is a map which is used to get the value from the index or key, not the contrary.


If you do many search with $country,you can flip the $iso_contries then use index to get the value.

$iso_countries = array
(
    'AF' => 'Afghanistan',
    'AX' => 'Aland Islands',
    'AL' => 'Albania',
    'DZ' => 'Algeria',
);
$iso_countries = array_flip($iso_countries);
$country = 'Algeria';
echo $iso_countries[$country];

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.