0

I have an array that I'm storing in a Session variable as follows:

[availableCountries] => Array
        (
            [Australia] => 1031
            [New Zealand] => 1027
            [USA] => 1029
            [Singapore] => 1026
            [Canada] => 1028
            [France] => 1030
        )

I have a variable that stores a selected key value, e.g.:

 $country = '1026';

I now need to get the name of the matching Country from the array, e.g. Singapore where $country = '1026'

3
  • 4
    php.net/manual/en/function.array-search.php ? Commented Jun 1, 2018 at 0:21
  • It's not clear how "LP1026" relates to 1026. Is the value stored in $country always prefixed with "LP" or is that prefix dynamic? Commented Jun 1, 2018 at 0:35
  • @Phil sorry that was a mistake, have edited it to remove the LP as it should just be "1026" as the value Commented Jun 1, 2018 at 0:38

2 Answers 2

2

What you're lookin for is array_search(), that provides the functionality you're looking for:

$key = array_search(str_replace("LP", "", $country), $yourArray);

Which returns: Singapore

If you're looking for a quick and dirty way to return the data (not recommended), then you could even do this:

echo array_flip($a)[str_replace("LP", "", $country)];

Provided the data is always present

Sign up to request clarification or add additional context in comments.

Comments

0

You can use array_search() function. It will search an array for a value and and return the key.

http://php.net/manual/en/function.array-search.php

$availableCountries = Array(

  'Australia' => 1031,
  'New Zealand' => 1027,
  'USA' => 1029,
  'Singapore' => 1026,
  'Canada' => 1028,
  'France' => 1030

);

function getCountry($array, $code){

  return array_search($code, $array);

}


echo getCountry($availableCountries, '1026'); //<---returns "Singapore"

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.