runningmark
runningmark

Reputation: 760

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);
    }
?>

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 ?

Upvotes: 1

Views: 85

Answers (4)

brslv
brslv

Reputation: 526

Here's another solution to the problem. It makes the matter_value an array and intersects it with every element of the $list array. If nothing matched, the result will be null.

function return_state($matter_value, $list) {
    foreach ($list as $list_item_key => $list_item) {
        if ( ! empty(array_intersect([$matter_value], array_values($list_item)))) {
            return $list_item_key;
        }
    }
}

Upvotes: 0

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

Use foreach loop and in_array function:

function return_state($matter_value = ""){
    $list = [
        'liquid' => ['water','soft drink'],
        'solid' => ['car','computer','floor'],
        'gas' => ['air','oxygen','carbon dioxide'],
    ];
    if (!empty($matter_value)) {   // avoids empty arguments
        foreach ($list as $key => $items) {
            if (in_array($matter_value, $items)) {
                return $key;
            }
        }
    }
    return false;
}

print_r(return_state("water"));   // "liquid"
print_r(return_state("floor"));   // "solid"

Upvotes: 1

Murad Hasan
Murad Hasan

Reputation: 9583

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.

Upvotes: 2

Disha V.
Disha V.

Reputation: 1864

array_search not able to find in inner arrays. It will look into main array i.e. liquid, solid, gas and its values (not an array). You need loop through keys of main array to search key.

<?php
    function return_state($matter_value,$list){
        foreach($list as $key=>$item){
            $test=array_search($matter_value, $item);
            if($test!==FALSE){
                return $key;
            }
        }
    }
?>

Upvotes: 0

Related Questions