PHP Exercises: Filter the collection using the given callback
PHP: Exercise-89 with Solution
Write a PHP program to filter the collection using the given callback.
Sample Solution:
PHP Code:
<?php
// Licence: https://bit.ly/2CFA5XY
// Function definition for 'reject' that takes an array of items and a filtering function as parameters
function reject($items, $func)
{
// Use 'array_filter' to filter the items based on the given function
// Use 'array_diff' to get the items that are not present in the filtered array
// Use 'array_values' to reindex the resulting array
return array_values(array_diff($items, array_filter($items, $func)));
}
// Call 'reject' with an array and an anonymous function filtering items with a length greater than 4, then display the result using 'print_r'
print_r(reject(['Green', 'Red', 'Black', 'White'], function ($item) {
return strlen($item) > 4;
}));
?>
Sample Output:
Array ( [0] => Red )
Flowchart:
PHP Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Write a PHP program to mutate the original array to filter out the values specified.
Next: Write a PHP program to return all elements in an given array except for the first one.
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