Thursday, February 5, 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
32481 POSTS0 COMMENTS
Milvus
126 POSTS0 COMMENTS
Nango Kala
6857 POSTS0 COMMENTS
Nicole Veronica
11982 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12069 POSTS0 COMMENTS
Shaida Kate Naidoo
6992 POSTS0 COMMENTS
Ted Musemwa
7230 POSTS0 COMMENTS
Thapelo Manthata
6940 POSTS0 COMMENTS
Umr Jansen
6923 POSTS0 COMMENTS