Reputation: 10649
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
Reputation: 78994
If you're looking in that specific column:
$found = array_search($letter, array_column($array, 'Find'));
unset($array[$found]);
Find
column and searchunset()
if Find
is not uniqueOr alternately:
$array = array_column($array, null, 'Find');
unset($array[$letter]);
Find
so you can just unset()
thatUpvotes: 4
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
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