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.
Recommended Posts:
- How to delete an array element based on key in PHP?
- Delete the array elements in JavaScript | delete vs splice
- PHP | unset() Function
- PHP | Unset() vs Unlink() Function
- How to delete last element from a map in C++
- How to delete last element from a set in C++
- PHP program to find missing element(s) from an array
- Replace each element by the difference of the total size of the array and frequency of that element
- Replace every array element by Bitwise Xor of previous and next element
- Replace every element of the array by its previous element
- Replace every element of the array by its next element
- How to unset JavaScript variables?
- Program to find the smallest element among three elements
- How to get the first element of an array in PHP?
- PHP | Second most frequent element in an array
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.



