Find Value Of Key In Associative Array

Wahyu Raja Butar-Butar Reply 11:53
I recently stumbled upon the following issue – I had an associative array with key=>value type and I wanted to get the value of a specific key. I wasn’t able to find a suitable built-in PHP function, so I decided to write something of my own. Feel free to reuse it however you like.
Include this function anywhere in your PHP file:
function find_by_key($searched, $array){
 if(!is_array($array)) return FALSE; // We haven't passed a valid array
 
 foreach($array as $key=>$value){
  if($key==$searched) return $value; // Match found, return value
 }
 return FALSE; // Nothing was found
}
Then you can use it by following this example:
$sample_array = array(
 'bmw'=>'fast',
 'mercedes'=>'luxury',
 'audi'=>'expensive'
);
 
echo find_by_key('audi', $sample_array);
This example should output ‘expensive’. I hope you find this useful.
source : http://ephp.info/get-by-key-associative-array

Related Posts

PHP 7262057258651721798
Comments
0 Comments
Facebook Comments by Media Blogger

Post a Comment

Search

Google+ Followers

Popular Posts

Translate