Wednesday, March 25, 2015

How To Search Key In Array And Return Its Value Using PHP?

You can get corresponding value associated with array key by using simple function as below.
function get_value_by_key($array,$key)
{
 foreach($array as $k => $each)
 {
   if($k == $key)
   {
     return $each;
   }
  
   if(is_array($each))
   {
     if($return = get_value_by_key($each,$key))
     {
       return $return;
     }
   }
  
  }
 
}

//creating array
$array = array
(
    '124' => 'Morning',
    '134' => 'Evening',
    '135' => 'Night'    
);

echo get_value_by_key($array,'124'); // outputs: Morning
echo get_value_by_key($array,'135'); // outputs: Night


This function loops through all the keys of an array and return the value associated with assigned variable $key.
Ref: http://stackoverflow.com/a/4467135

No comments:

Post a Comment