10

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"];
});
2
  • Please exactly describe what you want to do? Multidimensional arrays? array_filter() cannot handle them natively. You're looking for a single value inside an array? array_filter() is not the best way to do this because you can stop iteration when you found the value you've been looking for - array_filter() doesn't do that. Filter a set of values from a larger set? Most likely that array_filter() is faster than a hand-coded foreach-loop because it's a built-in function. Commented Jul 22, 2011 at 14:41
  • @Stefan Gehrig I added my sample array and code for array_filter . My point is should that be similar to doing a for loop or it can be faster ? My maximum array size is 30 . Commented Jul 22, 2011 at 14:54

5 Answers 5

31

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/

(archive: https://web.archive.org/web/20200930002558/https://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.

Sign up to request clarification or add additional context in comments.

2 Comments

Is this an answer, or a link to an answer? If the latter, it's off-topic.
Summary of the results that Levi Jackson posted at the link comparing for, foreach, while, and array_filter (foreach is fastest): foreach: 0.37 | while: 0.58 | for: 0.61 | array_filter: 0.74
21

I've made a test script because I was a little skeptical ...how can an internal function be slower than a loop...

But actually it's true. Another interesting result is that php 7.4 is almost 10x faster than 7.2!

You can try yourself

<?php
/*** Results on my machine ***
php 7.2
array_filter: 2.5147440433502
foreach: 0.13733291625977
for i: 0.24090600013733

php 7.4
array_filter: 0.057109117507935
foreach: 0.021071910858154
for i: 0.027867078781128

php 8.2
array_filter: 0.069692134857178
foreach: 0.018320083618164
for i: 0.019519329071045
**/

ini_set('memory_limit', '500M');
$data = range(0, 1000000);

// ARRAY FILTER
$start = microtime(true);
$newData = array_filter($data, function ($item) {
    return $item % 2;
});
$end = microtime(true);

echo "array_filter: ";
echo $end - $start . PHP_EOL;

// FOREACH
$start = microtime(true);
$newData = array();
foreach ($data as $item) {
    if ($item % 2) {
        $newData[] = $item;
    }
}
$end = microtime(true);

echo "foreach: ";
echo $end - $start . PHP_EOL;

// FOR
$start = microtime(true);
$newData = array();
$numItems = count($data);
for ($i = 0; $i < $numItems; $i++) {
    if ($data[$i] % 2) {
        $newData[] = $data[$i];
    }
}
$end = microtime(true);

echo "for i: ";
echo $end - $start . PHP_EOL;

5 Comments

That should be the accepted answer these days.
when it comes to dealing with a lot of calculation this would be a very acceptable answer. A few nanoseconds can matter!
As of PHP8.2 this still seems to be the case (3v4l.org/Zit6P)
I've added a benchmark for 8.2, thanks @rrr
I agree with @kaiserkiwi. Results for 8.2 is a good addition
7

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.

Comments

3

From my own experience, foreach is faster. I think it has something to do with function call overhead, arguments check, copy to variable return instruction, etc.. When using a basic syntax, the parsed code is more likely to be closer to the compiled/interpreted bytecodes, have better optimization down the core.

The common rule is : anything is simplier, run faster (imply less check, less functionnality, as long as it has all you need)

Comments

-5

Array_Filter

Iterates over each value in the input array passing them 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.

as for me same.

1 Comment

This is not what OP asked.

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.