The function seems okay. In Javascript one could use the method Array.every()
, but as this StackOverflow question illustrates there isn't really an equivalent method or functional approach in PHP that will stop the loop as soon as one element does not meet the requirement.
You might consider adhering to the PSR PHP Coding standards - especially PSR 12.
PSR-12 has a section about Lines:
There MUST NOT be a hard limit on line length.
The soft limit on line length MUST be 120 characters.
Lines SHOULD NOT be longer than 80 characters; lines longer than that SHOULD be split into multiple subsequent lines of no more than 80 characters each.
1
Readabillity suffers because the conditional line is a bit long, partly because of the indentation but also the additional spaces separating parentheses. It may not be an issue for anyone with a wide screen but as is visible in the code snippet one must scroll to the right to see the entire line. While it may only be a micro-optimization, one could pull out the strototime($date)
out to a variable, which would not only decrease function calls but also allow for a shorter line. Similarly the calls to strtotime()
for the start and end dates could be pulled out of the foreach
loop and stored in variables so they only need to be calculated once per function call and can decrease the length of that line with the conditional.
I question whether the third parameter having a default of an empty array is appropriate. If the function is called without any argument, then an empty array will be used and the function will return true
. Perhaps using type hinting would be a better technique:
function dates_in_range( string $start_date, string $end_date, array $dates) : bool {
Notice that method signature includes a return type declaration bool
. This was added in PHP 7.0 2. Hopefully your code is running on PHP 7.3 or newer, since those are the version that are officially supported 3.