MultiDev
MultiDev

Reputation: 10649

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.

Upvotes: 0

Views: 40

Answers (3)

AbraCadaver
AbraCadaver

Reputation: 78994

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

Upvotes: 4

avlnx
avlnx

Reputation: 676

If you want to search in the Find field, and return the corresponding ID field as in your example you want to have a match in the fourth line: $array[1]['Find'] = 'B';

Then you need to actually iterate the outer dimension like so:

foreach ($a in $array) {
  if ($a['Find'] == $letter) {
    // found, return the ID field
    return $a['ID'];
  }
}

Let me know if you want to return something else, hope this helps :)

Upvotes: 0

splash58
splash58

Reputation: 26153

Use array_filter to save only elements without B

$arrayWithoutB = array_filter($array, 
                function($i) use($letter){  return $i['Find'] != $letter; });

Upvotes: 2

Related Questions