Friday, October 24, 2025
HomeLanguagesPHP | Program to delete an element from array using unset() function

PHP | Program to delete an element from array using unset() function

Given an array of elements, we have to delete an element from the array by using the unset() function.

Examples:

Input : $arr = array("Harsh", "Nishant", "Bikash", "Barun");
        unset($arr[3]);
Output : Array
         (
           [0] => Harsh
           [1] => Nishant
           [2] => Bikash
         )

Input : $arr = array(1, 2, 6, 7, 8, 9);
        unset($arr[3]);
Output : Array
         (
           [0] => 1
           [1] => 2
           [2] => 6
           [4] => 8
           [5] => 9
         )

unset() function: The function accepts a variable name as parameter and destroy or unset that variable.

Approach: This idea to solve this problem using the unset function is to pass the array key of the respective element which we want to delete from the array as a parameter to this function and thus removes the value associated to it i.e. the element of an array at that index.

Below programs illustrate the above approach:

Program 1:




<?php
      
    $a = array("Harsh", "Bikash", "Nishant", "Barun", "Deep");
          
    // unset command accepts 3rd index and
    // thus removes the array element at
    // that position
    unset($a[3]);
      
    print_r ($a);
        
?>


Output:

Array
(
    [0] => Harsh
    [1] => Bikash
    [2] => Nishant
    [4] => Deep
)

Program 2:




<?php
      
    $a = array(1, 8, 9, 7, 3, 5, 4, );
      
    // unset command accepts 3rd index and
    // thus removes the array element
    // at that position
    unset($a[5]);
          
    print_r ($a);
        
?>


Output:

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

Note: The array keys will not be reordered after using the unset() function.

RELATED ARTICLES

Most Popular

Dominic
32361 POSTS0 COMMENTS
Milvus
88 POSTS0 COMMENTS
Nango Kala
6728 POSTS0 COMMENTS
Nicole Veronica
11892 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11954 POSTS0 COMMENTS
Shaida Kate Naidoo
6852 POSTS0 COMMENTS
Ted Musemwa
7113 POSTS0 COMMENTS
Thapelo Manthata
6805 POSTS0 COMMENTS
Umr Jansen
6801 POSTS0 COMMENTS