Sunday, June 14, 2026
HomeLanguagesPHP | Deleting an element from array using array_diff()

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
)
RELATED ARTICLES

Most Popular

Dominic
32515 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
6897 POSTS0 COMMENTS
Nicole Veronica
12013 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12109 POSTS0 COMMENTS
Shaida Kate Naidoo
7019 POSTS0 COMMENTS
Ted Musemwa
7262 POSTS0 COMMENTS
Thapelo Manthata
6976 POSTS0 COMMENTS
Umr Jansen
6964 POSTS0 COMMENTS