Open In App

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

Last Updated : 27 Apr, 2018
Improve
Improve
Like Article
Like
Save
Share
Report

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.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads