Array_filter in the context of an object, with private callback

berkes picture berkes · Nov 23, 2011 · Viewed 16.1k times · Source

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?

Answer

deceze picture deceze · Nov 23, 2011

Yes:

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

See the documentation for the callback type.