Gage M Gage M - 5 months ago 15
PHP Question

Not returning the next biggest value in my array

I have an array with a bunch of military times listed and I am trying to find the next closest value up to the current time. For example when it is 9:30 am it should return 9:40 am because that is the next biggest time but instead it will return 10:00 am no matter what time it is.

function closest($array, $number) {
sort($array);
foreach ($array as $a) {
if ($a >= $number) return $a;
}
return end($array);
}

$array = array(0730,0750,0810,0830,0840,0850,0900,0910,0920,0930,0940,0950,1000,1010,1020,1030,1040,1050,1100,1110,1120,1130,1140,1150,1210,1230,1250,1310,1330,1350,1410,1430,1450,1510,1530,1550,1610,1630,1650,1710,1720,1730,1740,1750,1800,1810,1820,1830,1840,1850,1900,1910,1920,1930,1940,1950,2000,2010,2020,2030,2040,2050,2100,2120,2140,2200,2220,2240,2300,2320);
$number = date("Hi");
$nexttime = closest($array, $number);

echo date("g:i a", strtotime("$nexttime"));


I have been through it many times trying to diagnose the problem, Trying to remove all of the zeros in front of the first few times returned an even stranger result of 7:00 pm.

Answer

I got an error with your array and prefixed numbers:

Parse error: Invalid numeric literal in (line number of array)...

You can define the values on array as string and cast them on the function with (int). See the following solution:

<?php
function closest($array, $number) {
    sort($array);
    foreach ($array as $a) {
       if ((int) $a > $number) return $a;
    }
    return end($array);
}

$array = array('0730','0750','0810','0830','0840','0850','0900','0910','0920','0930','0940','0950',1000,1010,1020,1030,1040,1050,1100,1110,1120,1130,1140,1150,1210,1230,1250,1310,1330,1350,1410,1430,1450,1510,1530,1550,1610,1630,1650,1710,1720,1730,1740,1750,1800,1810,1820,1830,1840,1850,1900,1910,1920,1930,1940,1950,2000,2010,2020,2030,2040,2050,2100,2120,2140,2200,2220,2240,2300,2320);

$nexttime = closest($array, '0930');
echo $nexttime;

Demo: http://ideone.com/TceTRb