How to remove an array element based on key in PHP
In this tutorial, we are going to see how to remove an array element based on key in PHP. 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 ) )