runningmark runningmark - 6 months ago 13
PHP Question

extracting key from given array with "value"

we have an array which looks something like this

<?php
$list = array(
'liquid'=>array('water','soft drink'),
'solid'=>array('car','computer','floor'),
'gas'=>array('air','oxygen','carbon dioxide'),
);
?>


now this is just an example list, what we are trying to achieve is

a user passes a value in a function like this

<?php
function return_state($matter_value){
return array_search($matter_value, $list);
}
?>



  • user passes
    water
    the result should be liquid

  • user passes
    floor
    the result should be solid




in short whatever user is passing it will return the key associated with it


but when we are executing this function, it returns ''(empty value).

What are we doing wrong ?

Answer

Just a foreach loop with in_array makes this easy.

$list = array(
        'liquid'=>array('water','soft drink'),
        'solid'=>array('car','computer','floor'),
        'gas'=>array('air','oxygen','carbon dioxide'),
    );
function return_state($matter_value, $list){    
    foreach($list as $key => $val){
        if(in_array($matter_value, $val))
            return $key;        
    }
    return 'Not found.';
}

echo return_state('floor', $list); //solid

Pass your array through the function call.

Comments