PHP Array Exercises : Delete a specific value from an array using array_filter() function
Write a PHP script to delete a specific value from an array using array_filter() function.
Sample Solution:
PHP Code:
<?php
// Associative array representing colors
$colors = array('key1' => 'Red', 'key2' => 'Green', 'key3' => 'Black');
// Value to be excluded from the array
$given_value = 'Black';
// Print the original array
print_r($colors);
// Use array_filter with an anonymous function to create a new array excluding the given value
$filtered_array = array_filter($colors, function ($element) use ($given_value) {
return ($element != $given_value);
});
// Print the original array (Note: This line contains a typo, it should be $filtered_array instead of $new_filtered_array)
print_r($filtered_array);
// Print the new array excluding the given value
print_r($filtered_array);
?>
Output:
Array ( [key1] => Red [key2] => Green [key3] => Black ) PHP Notice: Undefined variable: filtered_array in /home/stu dents/2f6e9db0-f423-11e6-a8c0-b738b9ff32f9.php on line 7 Array ( [key1] => Red [key2] => Green )
Flowchart:
PHP Code Editor:
Contribute your code and comments through Disqus.
Previous: Write a PHP function to filter a multi-dimensional array. The function will return those items that will match with the specified value.
Next: Write a PHP script to remove all white spaces in an array.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics