PHP | Deleting an element from array using array_diff()
Given an array, we have to delete an element from that array using the array_diff() function in PHP.
Examples:
Input : $arr = array(2, 8, 9, 7, 6, 5);
$arr = array_diff($arr, array(9));
Output : Array
(
[0] => 2
[1] => 8
[3] => 7
[4] => 6
[5] => 5
)
Input : $arr = array("shubham", "akshay", "vishal", "sweta");
$arr = array_diff($arr, array("akshay"));
Output : Array
(
[0] => shubham
[2] => vishal
[3] => sweta
)
array_diff() The array_diff() function accepts two or more than two arguments and returns an array containing values from the first array which are not present in other arrays.
Approach: The idea to solve this problem is we will pass two arrays to the array_diff() function as parameters. The first array in the parameter will be the array from which we want to delete the element. The second array will contain a single element which we want to delete from the first array. Finally, we will store the resultant array returned by the array_diff() function in the input array.
Below programs illustrate the above approach:
Program 1:
<?php $arr = array(2, 8, 9, 7, 6, 5); // returns the array after removing // the array value 9 $arr = array_diff($arr, array(9)); print_r ($arr); ?> |
Output:
Array
(
[0] => 2
[1] => 8
[3] => 7
[4] => 6
[5] => 5
)
Program 2:
<?php $arr = array("Harsh", "Nishant", "Akshay", "Barun", "Bikash"); // returns the array after removing // the array value "Akshay" $arr = array_diff($arr, array("Akshay")); print_r ($arr); ?> |
Output:
Array
(
[0] => Harsh
[1] => Nishant
[3] => Barun
[4] => Bikash
)
Recommended Posts:
- Replace each element by the difference of the total size of the array and frequency of that element
- Replace every array element by Bitwise Xor of previous and next element
- Replace every element of the array by its previous element
- Replace every element of the array by its next element
- Deleting all files from a folder using PHP
- Find the smallest after deleting given elements
- Find the largest after deleting the given elements
- Find the k smallest numbers after deleting given elements
- Find the k largest numbers after deleting the given elements
- Find the Largest Cube formed by Deleting minimum Digits from a number
- How to get the first element of an array in PHP?
- PHP | Second most frequent element in an array
- How to delete an array element based on key in PHP?
- Find the min/max element of an Array using JavaScript
- Replace every element of the array with BitWise XOR of all other
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



