0

The title can be a bit confusing, but how can you process an array and return the value of the key based on a value given. This is basically for an array library that converts database meta-data into human-readable format.

Example:

$countries = array('US'=>'United States','MX'=>'Mexico');

The above array would be considered an array library. So when I do a query and in my results I only have the two country code, I would then need to convert that into human-readable format. Is there a function that if I send it the two country code it will return the human-readable format. This function would then need to be reusable with other array libraries. Example function:

function covert_to_human($key, $array_library)
3
  • why not use use $array_library[$key] Commented Jun 19, 2013 at 22:17
  • what is the 'human-readable format' you wish to return? Commented Jun 19, 2013 at 22:17
  • lol @Orangepill I didn't think of that. I guess I was overlooking at it :/ Commented Jun 19, 2013 at 22:21

2 Answers 2

1

This will return the value associated with $key in $array_library if it exists otherwise will return an optional $default if the key is not in the $array_library

function convert_to_human($key, $array_library, $default = null){
     if (array_key_exists($key, $array_library)){
           return $array_library[$key];
     }
     return $default;
}

If you want a supper easy way to define and maintain a lookup, you can wrap this concept in a class and use parse_ini_file to seed the data.

class Lookup{
     protected $data;

     public function __construct($iniFile){
          $this->data = parse_ini_file($iniFile);
     }

     public function lookup($key, $default){
          return isset($this->data[$key])?$this->data[$key]:$default;
     }
}

To use you would author your lookup as

; Countries.ini 
US = "United States of America"
MS = "Mexico"
CA = "Canada"

Then create an instance of and use your class

$countryLookup = new Lookup("Countries.ini");
echo $countryLookup->lookup("MX", "Unknown Country");
Sign up to request clarification or add additional context in comments.

1 Comment

need to add a loop if he wants to send multiple $key values, which i think he deos
1
function convert_to_human($key, $library) {
    return array_key_exists($key, $library) ? $library[$key] : false;
}

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.