How to use array_filter function In PHP
The array_filter function can be used to filter elements of an array using a callback function. This approach allows you to remove specific keys by returning false for those keys in the callback function.
Program:
<?php
// Nikunj Sonigara
// Declare an associative array
$arr = array(
"1" => "Add",
"2" => "Multiply",
"3" => "Divide"
);
// Key to be removed
$keyToRemove = "1";
// Use array_filter to remove the key
$result = array_filter($arr, function($value, $key) use ($keyToRemove) {
return $key != $keyToRemove;
}, ARRAY_FILTER_USE_BOTH);
// Display the result
print_r($result);
?>
Output
Array ( [2] => Multiply [3] => Divide )
How to remove a key and its value from an associative array in PHP ?
Given an associative array containing array elements the task is to remove a key and its value from the associative array.
Examples:
Input : array( "name" => "Anand", "roll"=> "1")
Output : Array (
[roll] => 1
)
Input : array( "1" => "Add", "2" => "Multiply", "3" => "Divide")
Output : Array (
[2] => Multiply
[3] => Divide
)
Table of Content
- Using unset() function
- Using array_diff_key() function
- Using array_filter function