I have this array:
$fruits = [
['name' => 'banana', 'color' => 'yellow' , 'shape' => 'cylinder'],
['name' => 'apple', 'color' => 'red' , 'shape' => 'sphere'],
['name' => 'orange', 'color' => 'orange' , 'shape' => 'sphere'],
];
How can I find out if the array $fruits
already contains apple
in it?
I have tried: in_array("apple", $fruits)
and that didn't work out.
I also tried various syntax and messed a bit with array_key_exists()
, but nothing worked out. Any ideas?
PHP is notoriously unwieldy in such cases. The best all-around solution is a simple foreach
:
$found = false;
foreach ($fruits as $fruit) {
if ($fruit['name'] == 'apple') {
$found = true;
break;
}
}
if ($found) ....
You can write this in a number of sexier ways, but all of them will require additional memory allocation and/or will be slower; a good number of them will also be more difficult to understand if you are not very experienced.