JROB JROB - 6 months ago 10
PHP Question

Searching multidimensional array and returning 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. Any suggestions?

Answer

If you're looking in that specific column:

$found = array_search($letter, array_column($array, 'Find'));
unset($array[$found]);
  • This is a multidimensional array so extract the Find column and search
  • You need to loop and unset() if Find is not unique

Or alternately:

$array = array_column($array, null, 'Find');
unset($array[$letter]);
  • Extract all the columns but index them by Find so you can just unset() that