Search code examples
phparrayscountarray-filter

Best way to count coincidences in an Array in PHP


I have an array of thousands of rows and I want to know what is the best way or the best prectices to count the number of rows in PHP that have a coincidence on it.

In the example you can see that I can find the number of records that match with a range.

I´m thinking in this 2 options:

Option 1:

$rowCount = 0;
foreach ($this->data as $row) {
    if ($row['score'] >= $rangeStart && $row['score'] <= $rangeEnd) {
        $rowCount++;
    }
}
return $rowCount;

Option 2:

$countScoreRange = array_filter($this->data, function($result) {
    return $result['score'] >= $this->rangeStart && $result['score'] <= $this->rangeEnd;
});
return count($countScoreRange);

Thanks in advance.


Solution

  • it depends on what you mean when are you speaking about best practices?
    if your idea about best practice is about performance, it can say that there is one tradeoff that you must care about"

                                       **speed <===> memory** 
    

    if you need performance about memory :

    in this way : when you think about performance in iterating an iterable object in PHP, you can Use YIELD to create a generator function , from PHP doc :

    what is generator function ?

    A generator function looks just like a normal function, except that instead of returning a value, a generator yields as many values as it needs to. Any function containing yield is a generator function.

    why we must use generator function ?

    A generator allows you to write code that uses foreach to iterate over a set of data without needing to build an array in memory, which may cause you to exceed a memory limit, or require a considerable amount of processing time to generate.

    so it's better to dedicate a bit of memory instead of reserving an array of thousands

    Unfortunately:

    Unfortunately, PHP also does not allow you to use the array traversal functions on generators, including array_filter, array_map, etc.

    so till here you know if :

    1. you are iterating an array
    2. of thousands element
    3. especially if you use it in a function and the function runs many where.
    4. and you care about performance specially in memory usage.

    it's highly recommended to use generator functions instead.


    ** but if you need performance about speed :**

    the comparison will be about 4 things :

    1. for
    2. foreach
    3. array_* functions
    4. array functions (just like nexT() , reset() and etc.)

    The 'foreach' is slow in comparison to the 'for' loop. The foreach copies the array over which the iteration needs to be performed.

    but you can do some tricks if you want to use it :

    For improved performance, the concept of references needs to be used. In addition to this, ‘foreach’ is easy to use.

    what about foreach and array-filter ? as the previous answer said, also based on this article , also this : :

    it is incorrect when we thought that array_* functions are faster!

    Of course, if you work on the critical system you should consider this advice. Array functions are a little bit slower than basic loops but I think that there is no significant impact on performance.