Click here to Skip to main content
15,887,350 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have the following associative array:
PHP
$array = [
...
3 => '2023-01-01',
17 => '2023-08-26',
19 => '2023-08-15',
21 => '2023-09-01'
...
];

Values are dates in YYYY-MM-DD format.

I need to get all keys whose value is > current date.

I've found two solutions:

#1:
PHP
$filtered = [];
foreach ($array as $key => $val) {
	if ($val > date('Y-m-d')) array_push($filtered, $key);
}

#2:
PHP
$filtered = array_keys(array_filter($array, fn($v) => $v > date('Y-m-d')));

Which one is the best in terms of performance? And are there other (better) ways?

What I have tried:

#1:
PHP
$filtered = [];
foreach ($array as $key => $val) {
	if ($val > date('Y-m-d')) array_push($filtered, $key);
}

#2:
PHP
$filtered = array_keys(array_filter($array, fn($v) => $v > date('Y-m-d')));
Posted
Updated 23-Aug-23 1:14am
v3

1 solution

The performance difference between your two solutions will be very similar for small arrays.

Your foreach solution might have a slight edge in terms of readability as it uses a traditional foreach loop, and it explicitly pushes keys to the result array. This can be easier to understand but we are nitpicking here.

Your array_keys solution that uses array_filter combined with array_keys, which is a concise and functional approach can be appealing to developers who are comfortable with functional programming, but again, we are nitpicking.

In a case where you have to handle very large arrays (50 000+), the performance impact may become more noticeable, the only limitation will be your Memory_limit. If you have a too big array, it will give you an error like: Out Of Memory, but it really has to be very large! An alternative, which might be slightly more efficient for very large arrays, is to use a combination of array_reduce and array_filter as in:
PHP
$filtered = array_reduce(
    array_keys($array),
    function ($result, $key) use ($array) {
        if ($array[$key] > date('Y-m-d')) {
            $result[] = $key;
        }
        return $result;
    },
    []
);


I doubt, however, that you will ever have to revert to this in your case.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900