You are here: Home / Topics / How to remove an array element based on key in PHP

How to remove an array element based on key in PHP

Filed under: PHP on 2023-07-02 21:13:13

The unset() function is used to remove an element from an array. The unset() function is used to destroy any other variable and similarly to remove an element from an array. This function takes the array key as input and removes that element from the array. After removal, the associated key and value do not change.
 

Remove an element from a one-dimensional array
 

<?php 
 $arr = array('A', 'B', 'C', 'D', 'E'); 
    
 unset($arr[2]); 
   
 print_r($arr); 
?>
 

Output:

Array ( [0] => A [1] => B [3] => D [4] => E )
 

 

Remove an element from an associative array
 

<?php  
 $school = array(  
    
   "prof1" => array(  
     "name" => "Jean",  
     "age" => 54,  
   ),  
   "prof2" => array(  
     "name" => "Thomas",  
     "age" => 41,  
   ),   
   "prof3" => array(  
     "name" => "Alex",  
     "age" => 32,  
   ),    
 );  
 unset($school["prof2"]); 
 print_r($school);  
?>
 

Output:

Array ( 
[prof1] => Array ( 
 [name] => Jean 
 [age] => 54 

[prof3] => Array ( 
 [name] => Alex 
 [age] => 32 

)

About Author:
Y
Yatendra Sir     View Profile
Hi, I am using MCQ Buddy. I love to share content on this website.