How Remove Element from Array in PHP
PHP unset() function uses to remove element from array in PHP using array key.
Example 1
$fruits=array('Apple','Mango',''Orange','Avacado','Banana');
unset($fruits[1]); // Index 1 which is Mango will be removed from the PHP $fruits array
print_r($fruits);
Array ( [0] => Apple [2] => Orange [3] => Avocado [4] => Banana )
Example 2
$capitals['UK'] = 'London';
$capitals['Germany'] = 'Berlin';
$capitals['France'] = 'Paris';
$capitals['Australia'] = 'Canberra';
unset($capitals['UK']); // element UK will be removed from the PHP array $capitals
print_r($capitals);
Array ( [Germany] => Berlin [France] => Paris [Australia] => Canberra )
It is also possible to remove multiple elements at the same time, by passing more than one array key with PHP unset function.
$fruits=array('Apple','Mango',''Orange','Avacado','Banana');
unset($fruits[0],$fruits[2]); // This will delete Both Apple and orange elements from the PHP $fruits array
print_r($fruits);
Array ( [1] => Mango [3] => Avocado [4] => Banana )
Remove Array Element by Value
array_search function returns the array key for a given value. Then we can use the unset function to remove the corresponding key from the PHP array.
$fruits=array('Apple','Mango',''Orange','Avacado','Banana');
$key = array_search('Mango', $fruits);
unset($fruits[$key]);
print_r($fruits);
Array ( [0] => Apple [2] => Orange [3] => Avocado [4] => Banana )