1

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?

6
  • array_reduce will reduce your array to a single value you can use array_filter instead and pass your is_valid method to it Commented Apr 15, 2017 at 3:26
  • OP does not want a callback function @Amr Aly Commented Apr 15, 2017 at 3:29
  • @AmrAly I got confused between array_reduce and array_filter. I was basically looking for a way to filter an array of objects without creating a callback function. Commented Apr 15, 2017 at 3:31
  • so you want built-in function to retrieve your array and return only the valid ones without any callbacks Commented Apr 15, 2017 at 3:32
  • @AmrAly Yes. Basically a built-in function without any callbacks. Commented Apr 15, 2017 at 3:41

4 Answers 4

4

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(); } );
Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

2

You can use this one liner:

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

from this library

Comments

1

Use this:

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

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

3 Comments

As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.
I had a quicklook; strpos returns the position number of the occurrence of the string 'PPC'. This code needs to be explained, haven't looked into the logic if it even works.
Just copy some code from my project. In this case, the function function ($item) { return strpos($item->ItemCode,'PPC');} will return true for the position of array members that match condition.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.