How to Delete an Array Element Based On key In PHP
Posted By
Bajarangi soft ,
Posted On 31-12-2020
Given an array (One dimensional or multidimensional) and the task is to delete an array element based on key value,Using unset() Function: The unset() function is used to remove element from the array. The unset function is used to destroy any other variable and same way use to delete any element of an array. This unset command takes the array key as input and removed that element from the array. After removal the associated key and value does not change.
Syntax:
Parameter: This function accepts single parameter variable. It is required parameter and used to unset the element.
Examples:
Input: Array
(
[0] => 'G'
[1] => 'E'
[2] => 'E'
[3] => 'K'
[4] => 'S'
)
Key = 2
Output: Array
(
[0] => 'G'
[1] => 'E'
[3] => 'K'
[4] => 'S'
)
Program 1: Delete an element from one dimensional array.
<?php
//program delete an array element based on index
//declare arrr variables and initialize it
$arr=array('s','i','r','i');
//display the array elements
print_r($arr);
//use unset()function delete
unset($arr[2]);
//display the array element
print_r($arr);
?>
Program 2: Delete an element from associative array.
<?php
$marks=array("ankit"=>array("c"=>89,"science"=>80),"ram"=>array("d"=>45,"science"=>98),"anoop"=>array("c"=>50,"science"=>70));
print_r($marks);
unset($marks['ram']);
echo "after delete the element <br> <br>";
print_r($marks);
?>