Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array_filter in the context of an object, with private callback

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?

like image 295
berkes Avatar asked Nov 23 '11 09:11

berkes


People also ask

What is array_filter PHP?

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.

How do you filter an array key?

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.

How to use array filter PHP?

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.


1 Answers

Yes:

return array_filter($this->get_docs(), array($this, 'filter_item'));

See the documentation for the callback type.

like image 193
deceze Avatar answered Oct 14 '22 18:10

deceze