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:

filter_none

edit
close

play_arrow

link
brightness_4
code

<?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);
      
?>

chevron_right


Output:

Array
(
    [0] => 2
    [1] => 8
    [3] => 7
    [4] => 6
    [5] => 5
)

Program 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

<?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);
      
?>

chevron_right


Output:

Array
(
    [0] => Harsh
    [1] => Nishant
    [3] => Barun
    [4] => Bikash
)


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

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.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.