How to use array_diff() Function In PHP
The array_diff() function compares arrays and returns the values in the first array that are not present in any of the other arrays. This can be used to remove specific elements by value.
Example: The array_diff() function removes the element “CSS” from the array.
<?php
$arr = ["HTML", "CSS", "JavaScript", "PHP"];
$remVal = "CSS";
$arr = array_diff($arr, [$remVal]);
print_r($arr);
?>
Output
Array ( [0] => HTML [2] => JavaScript [3] => PHP )
Remove Specific Element from an Array in PHP
Given an Array containing some elements, the task is to remove specific elements from the array in PHP.
Below are the approaches to remove specific elements from an array in PHP:
Table of Content
- Using unset() Function
- Using array_diff() Function
- Using array_filter() Function
- Using array_splice() Function
- Using foreach Loop