moustiluigi moustiluigi - 11 days ago 5
PHP Question

Get key from value in multidimentionnal array

I have an array of 1500 english synonyms formatted as follows:

array(1521) {
[0]=>
array(2) {
[0]=>
string(5) "April"
[1]=>
string(3) "Apr"
}
[1]=>
array(7) {
[0]=>
string(5) "China"
[1]=>
string(26) "People's Republic of China"
[2]=>
string(14) "mainland China"
[3]=>
string(15) "Communist China"
[4]=>
string(9) "Red China"
[5]=>
string(3) "PRC"
[6]=>
string(6) "Cathay"
}
[2]=>
array(2) {
[0]=>
string(8) "December"
[1]=>
string(3) "Dec"
}
[3]=>
array(4) {
[0]=>
string(5) "Earth"
[1]=>
string(5) "earth"
[2]=>
string(5) "world"
[3]=>
string(5) "globe"
}

...

[1519]=>
array(2) {
[0]=>
string(4) "year"
[1]=>
string(10) "solar year"
}
[1520]=>
array(2) {
[0]=>
string(4) "zero"
[1]=>
string(4) "null"
}
}


I'm trying to make a function which takes a word and returns the sub-array key

Ex:

$result = get_synonym_family($array, "world");
echo $result; //3


I tried to combine some of the examples I found on the already existing stackoverflow questions but nothing was fitting my needs

Answer

You can use the foreach function to walk-over all the values in the array, and then use the in_array function to check if the value exists in the inner-array:

function get_synonym_family($array, $word) {
    foreach($array as $key => $sub_array) {
        if (in_array($word, $sub_array)) {
            return $key;
        }
    }

    return false;
}
Comments