Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search Array : array_filter vs loop

I am really new in PHP and need a suggestion about array search.

If I want to search for an element inside a multidimensional array, I can either use array_filter or I can loop through the array and see if an element matching my criteria is present.

I see both suggestion at many places. Which is faster? Below is a sample array.

Array ( 
  [0] => Array ( 
    [id] => 4e288306a74848.46724799
    [question] => Which city is capital of New York?
    [answers] => Array ( 
      [0] => Array ( 
        [id] => 4e288b637072c6.27436568 
        [answer] => New York 
        [question_id_fk] => 4e288306a74848.46724799 
        [correct] => 0 
      ) 
      [1] => Array ( 
        [id] => 4e288b63709a24.35955656 
        [answer] => Albany 
        [question_id_fk] => 4e288306a74848.46724799 
        [correct] => 1 
      ) 
    )
  )
)

I am searching like this.

$thisQuestion = array_filter($pollQuestions, function($q) {
  return questionId == $q["id"];
});
like image 748
Pit Digger Avatar asked Jul 22 '11 14:07

Pit Digger


People also ask

Is array_filter faster than forEach?

I know it's an old question, but I'll give my two cents: for me, using a foreach loop was much faster than using array_filter. Using foreach, it took 1.4 seconds to perform a search by id, and using the filter it took 8.6 seconds. Show activity on this post. From my own experience, foreach is faster.

Is array filter faster than for loop?

To our surprise, for-loops are much faster than the Array. filter method. To be precise, the Filter method is 77% slower than for loop.

How do you filter an array key?

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.

Is filter a loop JS?

filter() for that. The way filter works is you loop over every single item in an array, and you either say yes (true) or no (false). If you return true that item will be in the array subset, if you return false it will take out that item from the array that is returned.


1 Answers

I know, the question is old, but I disagree with the accepted answer. I was also wondering, if there was a difference between a foreach() loop and the array_filter() function and found the following post:

http://www.levijackson.net/are-array_-functions-faster-than-loops/

Levi Jackson did a nice job and compared the speed of several loop and array_*() functions. According to him a foreach() loop is faster than the array_filter() function. Although it mostly doesn't make such a big difference, it starts to matter, when you have to process a lot of data.

like image 168
user3888130 Avatar answered Oct 23 '22 05:10

user3888130