phparraysmultidimensional-arrayfilter

Get the first level key of a 2d array row with a qualifying value in a specified column


I am trying to search for the value in a column of a 2d array. My array structure is:

[
    2 => ["HEADER"],  
    3 => ["ACCESSION #", "F4216027"],
    4 => ["ACTIVATION CODE", "PGMWZ-PUSUU"],
    5 => ["CUSTOMER FIRST NAME","JAMES"]
]

If I am trying to search "CUSTOMER FIRST NAME". I tried with below function, but with no result.

function searchForValue($id, $array) {
   foreach ($array as $key => $val) {
       if ($val[0] === $id) {
           return $key;
       }
   }
   return null;
}

And expected output is the key of parent index: [5]


Solution

  • Simple solution using foreach and in_array function:

    $search_word = "CUSTOMER FIRST NAME";
    $parent_key = null;
    
    // $arr is your initial array
    foreach ($arr as $k => $v) {
        if (in_array($search_word, $v)) $parent_key = $k;
    }
    
    print_r($parent_key);  // 5