Question

I am trying to populate a dropdown list with quarter hour times. The key being the option value, and the value being the option text.

private function quarterHourTimes() {
      $formatter = function ($time) {
          return date('g:ia', $time);
      };
      $quarterHourSteps = range(25200, 68400, 900);

      return array_map($formatter, $quarterHourSteps);
}

The problem is that the above function works, but does not seem to work as an associative array. Is there an elegant solution for this problem?

For the key, I wish to have the time in the following format date('H:i', $time);

e.g. array should look like this:

$times = 
[
    ['07:00' => '7:00am'],
    ['07:15' => '7:15am'],
    ['07:30' => '7:30am'],
    ['07:45' => '7:45am'],
    ['08:00' => '8:00am'],
    ['08:15' => '8:15am'],
    ...
];

My Solution - Dump the array_map:

private function myQuarterHourTimes()
{


    $quarterHourSteps = range(25200, 68400, 900);

    $times = array();
    foreach(range($quarterHourSteps as $time)
    {
        $times[date('H:i', $time)] = date('g:ia', $time);
    }

    return $times;
}
Was it helpful?

Solution

Your function can be easily replaced with:

$result = array_reduce(range(25200, 68400, 900), function(&$cur, $x)
{
   $cur[date('H:i', $x)] = date('g:ia', $x);
   return $cur;
}, []);

with result in associative array like this.

OTHER TIPS

I suppose you are looking for something like this

<?php
function formatter($time) {
          return array (date('g:i', $time) => date('g:ia', $time));
      };

 function quarterHourTimes() {

      $quarterHourSteps = range(25200, 68400, 900);

      return array_map('formatter', $quarterHourSteps);
}

print_r (quarterHourTimes());

?>

Demo

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top