PHP

Remove an Element by its Value from a PHP Array

Discover how to remove a specific element from a PHP array based on its value, using a combination of array_search() and unset(). Ideal for precise data manipulation.

<?php
$fruits = ['apple', 'banana', 'orange', 'grape', 'banana'];
$value_to_remove = 'banana';

// Find the first occurrence of the value
$key_to_remove = array_search($value_to_remove, $fruits);

// If found, remove it
if ($key_to_remove !== false) {
    unset($fruits[$key_to_remove]);
}

// Re-index the array if necessary (for indexed arrays)
$fruits = array_values($fruits);
print_r($fruits);

// To remove all occurrences of a value:
$all_fruits = ['apple', 'banana', 'orange', 'grape', 'banana'];
$all_fruits = array_diff($all_fruits, [$value_to_remove]);
$all_fruits = array_values($all_fruits); // Re-index
print_r($all_fruits);
?>
How it works: This snippet shows two ways to remove elements by value. The first uses `array_search()` to find the key of the first occurrence of a value, and then `unset()` to remove it. If you need to remove *all* occurrences of a specific value, `array_diff()` is a more concise option. After removal with `unset()` or `array_diff()`, `array_values()` is often used to re-index the array, ensuring consecutive numerical keys.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs