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:

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:

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

Program 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


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.



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.