21

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?

tereško
  • 58,060
  • 25
  • 98
  • 150
berkes
  • 26,996
  • 27
  • 115
  • 206

1 Answers1

63

Yes:

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

See the documentation for the callback type.

deceze
  • 510,633
  • 85
  • 743
  • 889
  • 4
    Great info! If you are using static methods you will have to pass in the class name with the filter function. To do this you can replace `array($this, 'filter_item')` with `array(__CLASS__, 'filter_item')`. – Kevin M Oct 05 '12 at 16:41
  • Will the filter_item() method be called on the object that calls array_filter(), or on each object in $this->get_docs()? – Arild Jul 29 '14 at 07:27
  • 1
    @Arild Essentially, `$this->filter_item($doc)` will be called for each item returned from `get_docs()`. – deceze Jul 29 '14 at 07:38
  • all i'm reading is deceze php answers today, thank god you're on this site man, seriously.. – Robert Sinclair Aug 16 '17 at 01:19