PHP Array, get the key based on a value -


if have array

$england = array(         'avn' => 'avon',         'bdf' => 'bedfordshire',         'brk' => 'berkshire',         'bkm' => 'buckinghamshire',         'cam' => 'cambridgeshire',         'chs' => 'cheshire' ); 

i want able 3 letter code full text version, how write following function:

$text_input = 'cambridgeshire'; function get_area_code($text_input){     //cross reference array here     //fish out key, in case 'cam'     return $area_code; } 

thanks!

use array_search():

$key = array_search($value, $array); 

so, in code:

// returns key or false if value hasn't been found. function get_area_code($text_input) {     global $england;     return array_search($england, $text_input); } 

if want case insensitive, can use function instead of array_search():

function array_isearch($haystack, $needle) {    foreach($haystack $key => $val) {        if(strcasecmp($val, $needle) === 0) {            return $key;        }    }    return false; } 

if array values regular expressions, can use function:

function array_pcresearch($haystack, $needle) {    foreach($haystack $key => $val) {        if(preg_match($val, $needle)) {            return $key;        }    }    return false; } 

in case have ensure values in array valid regular expressions.

however, if values coming <input type="select">, there's better solution: instead of <option>cheshire</option> use <option value="chs">cheshire</option>. form submit specified value instead of displayed name , won't have searching in array; you'll have check isset($england[$text_input]) ensure valid code has been sent.


Comments

Popular posts from this blog

asp.net - repeatedly call AddImageUrl(url) to assemble pdf document -

java - Android recognize cell phone with keyboard or not? -

iphone - How would you achieve a LED Scrolling effect? -