I'v got this array:
$by_date = array(
"2018-10-05"=>54,
"2018-10-07"=>20,
"2018-10-08"=>31,
"2018-10-12"=>52
);
I want to get value by date, but if the date doesn't exist get the lowest date value
for example:
if the date is "2018-10-07
" I'll get 20
and if the date is "2018-10-10
" I'll get 31
that can go to bigger differences between the date and the last key in the array
For example, if the date is "2019-01-25
" I'll get 52 because "2018-10-12
" is the last key in the array.
Thanks for the help :)
You can do it with a simple if condition that uses isset() to check for your input as a key on the array. If the condition is met, you return the matched value, otherwise, use max() and array_keys() to return the value with the highest key.
$by_date = array(
"2018-10-05"=>54,
"2018-10-07"=>20,
"2018-10-08"=>31,
"2018-10-12"=>52
);
$testVal = '2018-10-12'
if (isset($by_date[$testVal]))
return $by_date[$testVal];
else
return $by_date[max(array_keys($by_date))];
You guys where right the previews answer wasn't good enough
I'v made a work around that works for me, not sure about efficiency
if (!isset($by_date[$testVal])){
$by_date[$testVal] = null;
ksort($by_date);
$date_key = array_search($price_date,array_keys($by_date));
$by_date[$testVal] = (array_values($by_date)[$date_key-1]);
}
$by_date_price = $by_date[$testVal];
Thank you for the help and comments