PHP
Remove Elements Present in Another Array
Learn to remove elements from a PHP array that are also present in a second array using `array_diff()`, useful for filtering lists.
<?php
$allFruits = ['apple', 'banana', 'orange', 'grape', 'kiwi', 'pear'];
$unavailableFruits = ['banana', 'grape', 'mango']; // mango is not in allFruits
// Get fruits that are available (i.e., not in unavailableFruits)
$availableFruits = array_diff($allFruits, $unavailableFruits);
echo "All Fruits:
";
print_r($allFruits);
echo "
Unavailable Fruits:
";
print_r($unavailableFruits);
echo "
Available Fruits (after removing unavailable):
";
print_r($availableFruits);
// Example with numeric keys and values
$numbers1 = [1, 2, 3, 4, 5, 6];
$numbersToRemove = [3, 5, 7];
$remainingNumbers = array_diff($numbers1, $numbersToRemove);
echo "
Remaining Numbers:
";
print_r($remainingNumbers);
?>
How it works: This snippet demonstrates `array_diff()`, a useful PHP function for comparing two or more arrays and returning the values from the first array that are not present in any of the other arrays. This is excellent for scenarios like filtering out blacklisted items or finding unique elements that exist in one set but not another. Note that `array_diff()` compares values, not keys.