Sudar
Sudar

Reputation: 20000

array_filter on object arrays

I have an array of objects. The objects have a is_valid method that has some internal logic and returns either a boolean.

Now I want to get all objects in the array that return true to is_valid. I can do it using a foreach loop.

But is there way to do it using array_filter in PHP without creating a new anonymous or callback function?

Upvotes: 1

Views: 7103

Answers (4)

Will Nguyen
Will Nguyen

Reputation: 21

Use this:

$Filtered = array_filter($table, function ($item) {               
    return strpos($item->ItemCode,'PPC');
}); 

This returns an array of objects, that have ItemCode like PPC.

Upvotes: 1

Minwork
Minwork

Reputation: 1022

You can use this one liner:

 Arr::filterObjects($array, 'is_valid')

from this library

Upvotes: 2

maltere
maltere

Reputation: 41

You will not be able to achive this without an anonymous callback function, as bestprogrammerintheworld said

so if you'd still like to use array_filter, this may be your answer:

array_filter($array, function($entry) { return $entry->is_valid(); } );

Upvotes: 4

bestprogrammerintheworld
bestprogrammerintheworld

Reputation: 5520

The answer is no? http://php.net/manual/en/function.array-filter.php

array_filter

(PHP 4 >= 4.0.6, PHP 5, PHP 7) array_filter — Filters elements of an array using a callback function

Upvotes: 2

Related Questions