/ Published in: PHP
Released to the public domain. Example: you have an array, $seasons = array('Summer' => array('June', 'July', 'August'), 'Autumn' => array('September', 'October', 'November'), 'Winter' => array('December', 'January', 'February'), 'Spring' => array('March', 'April', 'May'));. Running print_r(find_keys_based_on_value('October', $seasons)); will is equivalent to print_r(array('Autumn' => array('September', 'October', 'November');. By default, the script will keep searching until it reaches the end of the array. To stop at the first match, call with $first_only set to true. To return only the key name(s), call with $key_names_only set to true.
Expand |
Embed | Plain Text
function find_keys_based_on_value($value, $array, $first_only = false, $key_names_only = false) { foreach($array as $parent_key_name => $parent_key_values) { if(db::fast_is_array($parent_key_values)) { foreach($parent_key_values as $key_value) { if($key_value==$value) { if($first_only) return $key_names_only ? $parent_key_name : $parent_key_values; // return first key matched; exit function else $results[] = $key_names_only ? $parent_key_name : $parent_key_values; // keep result for output later } } } } return $results; // function will have stopped execution if $first_only = true, so it must be false }
You need to login to post a comment.
