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:
$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.