Reputation: 3873
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)
Upvotes: 0
Views: 85
Reputation: 24655
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");
Upvotes: 1
Reputation: 6269
function convert_to_human($key, $library) {
return array_key_exists($key, $library) ? $library[$key] : false;
}
Upvotes: 1