The Wayback Machine - https://web.archive.org/web/20231211184005/https://www.geeksforgeeks.org/php-program-delete-element-array-using-array_diff-function/
Open In App
Related Articles

PHP | Deleting an element from array using array_diff()

Improve Article
Improve
Save Article
Save
Like Article
Like

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
)

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Last Updated : 27 Apr, 2018
Like Article
Save Article
Previous
Next
Similar Reads
Complete Tutorials