← Back to all snippets
PHP

Remove Specific Values from an Array

Learn how to easily remove one or more specific values from a PHP array using `array_diff`, ensuring the remaining elements are re-indexed if needed.

<?php
$data = ['apple', 'banana', 'orange', 'apple', 'grape', 'banana'];
$valuesToRemove = ['apple', 'banana'];

// Using array_diff to remove specific values
$filteredData = array_diff($data, $valuesToRemove);

// array_diff preserves keys, so re-index if desired
$reIndexedData = array_values($filteredData);

print_r($reIndexedData);

echo "
";

$numbers = [10, 20, 30, 40, 10, 50];
$singleValueToRemove = [10];

$resultNumbers = array_values(array_diff($numbers, $singleValueToRemove));

print_r($resultNumbers);
?>
How it works: This snippet demonstrates how to remove specific values from an array using `array_diff()`. `array_diff()` compares arrays and returns all values from the first array that are not present in any of the other arrays. Since `array_diff()` preserves the original keys, `array_values()` is then used to re-index the array numerically, ensuring a clean, sequential index for the resulting array.

Need help integrating this into your project?

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

Hire DigitalCodeLabs