Deleting an element from a PHP array by value (not by key)
Hello everyone! I just started learning PHP and ran into a problem. I have an array with numbers:
```php
$fruits = ['apple', 'banana', 'cherry', 'date', 'banana'];
```
I need to delete an element with the value 'banana' from it. But the problem is that I don't know which index it is at. All the examples I find show deletion by key using `unset($array[2])`, but my key is unknown.
I tried writing a loop, but it doesn't work correctly — it only deletes the first element, and the second 'banana' remains. Or it completely breaks the array indices. I need ALL elements with the value 'banana' to be deleted.
Here's what I tried:
```php
foreach ($fruits as $key => $value) {
if ($value === 'banana') {
unset($fruits[$key]);
}
}
```
This seems to work, but
No answers yet.
Log in to leave an answer
Blogs