phparraysmultidimensional-arrayfilter

Search for a column value in a 2d array and return its first level key


I am trying to see if a certain value exists in this array, and if so, return the key:

$letter = 'B';

$array[0]['ID'] = 1;
$array[0]['Find'] = 'A';
$array[1]['ID'] = 2;
$array[1]['Find'] = 'B';

$found = array_search($letter, $array);
    
if ($found) { 
  unset($array[$found]);
}

From what I can tell, this is not dropping the array elements when the value is found.


Solution

  • If you're looking in that specific column:

    $found = array_search($letter, array_column($array, 'Find'));
    unset($array[$found]);
    

    Or alternately:

    $array = array_column($array, null, 'Find');
    unset($array[$letter]);