2

I have an array of numbers ranging from 0-23, each number representing the time from midnight to 11PM. It's ordered descending by the key's value.

22 => int 8
3 => int 7
5 => int 6 

etc. If, for example, the array's first element's key is 22 I'd like the variable $first to be "10PM".

Sure, I could write:

if(key($array)=='22'){
    $first = '10PM';
}

but I'd have to do that 23 times for each key...is there an easier way?

Hook
  • 305
  • 3
  • 12
  • Why use an array? And where does "22" come from? Are you not working with a date or timestamp? Check out http://stackoverflow.com/questions/3404699/how-to-get-am-pm-from-a-datetime-in-php – Naruto Oct 12 '15 at 10:02
  • try this -http://www.php-mysql-tutorial.com/wikis/php-tutorial/php-12-24-hour-time-converter-part-1.aspx – marmeladze Oct 12 '15 at 10:07
  • Thanks guys, the "22" is from an automated array given to me from the Facebook Insights data array for "fans online". They lay out the number of people online, and at what time, by those numbers in my example. – Hook Oct 12 '15 at 10:15

4 Answers4

1
$array = array(
    22 => 8,
    3  => 7,
    5 => 6    
);

$i = 1;
foreach ($array $key=>$val)
{
    ${'time_' . $i} = date("HA", strtotime($key . ":00:00"));
    $i++;
}

//Now check echo $time_1;
Al Amin Chayan
  • 2,460
  • 4
  • 23
  • 41
1

You can also pass your values to a function like bellow:

<?php

$array = array(22 => 8, 3 => 7, 5 => 6);

foreach ($array as $key => $value) {
    echo numbers_to_time($key) . "<br>";
}

function numbers_to_time($number) {

    $number = intval($number);

    if ($number < 0 || $number > 23) {
        return "Number should be between 1 to 23";
    }


    if ($number == 0) {
        return "12AM";
    } elseif ($number == 12) {
        return $number . "PM";
    } elseif($number > 0 && $number < 12) {
        return $number ."AM";
    } elseif ($number > 12 && $number <= 23) {
        $temp = $number - 12;
        return $temp . "PM";
    }

}

?>
Sazzadur Rahman
  • 2,650
  • 1
  • 18
  • 34
1

Here is the code

$hrs = 15;
echo date("h a", strtotime("00-00-00 $hrs:00:00"));
Mitul
  • 3,431
  • 2
  • 22
  • 35
-2

You can achieve this with below code.

$array = array(
   22 => 8,
   3  => 7,
   5 => 6    
);

foreach($array as $key => $val){    
   if(($key/12) <1 ){
       $time = $key."AM";
   } else if(($key/12) == 1 ){
         $time = "12"."PM";
   } else{
     $time = ($key%12)."PM"; 
   }
   echo $time;
}
sandeepsure
  • 1,113
  • 1
  • 10
  • 17