I want to filter an array, using the array_filter function. It hints at using call_user_func under water, but does not mention anything about how to use within the context of a class/object.
Some pseudocode to explain my goal:
class RelatedSearchBlock {
//...
private function get_filtered_docs() {
return array_filter($this->get_docs(), 'filter_item');
}
private filter_item() {
return ($doc->somevalue == 123)
}
}
Would I need to change 'filter_item'
into array($this, 'filter_item')
? Is what I want possible at all?
The array_filter() function filters the values of an array using a callback function. This function passes each value of the input array to the callback function. If the callback function returns true, the current value from input is returned into the result array. Array keys are preserved.
Filtering a PHP array by keys To use the PHP array_filter() function to filter array elements by key instead of value, you can pass the ARRAY_FILTER_USE_KEY flag as the third argument to the function. This would pass the key as the only argument to the provided callback function.
To filter an array in PHP, use the array_filter() method. The array_filter() takes an array and filter function and returns the filtered array. The filter function is a custom user-defined function with its logic and based on that, it filters out the array values and returns them.
Yes:
return array_filter($this->get_docs(), array($this, 'filter_item'));
See the documentation for the callback
type.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With