i have an array of hours[] and minutes[].
hours Array:
Array ( [0] => 11 [1] => 12 [2] => 13 [3] => 14 )


minutes[] Array:
Array ( [0] => 30 [1] => 30 [2] => 30 [3] => 30 )

now i want an array which will merge hours[] and time[] and give me an time[] array someting like below:

time Array:
Array ( [0] => 11:30 [1] => 12:30 [2] => 13:30 [3] => 14:30 )

how can i do it...

Dani AI

Generated

Both and correctly pair each hour with its minute using a loop. A few practical improvements make the result safer and more useful years later: handle arrays of different lengths, ensure minutes are two digits (so 11:05 not 11:5), cast and validate inputs, and decide whether the output should be plain strings or DateTime objects for later arithmetic.

A concise, modern way is to use array_map with sprintf to guarantee formatting:

$times = array_map(
    function($h, $m) {
        return sprintf('%d:%02d', (int)$h, (int)$m);
    },
    $hours,
    $minutes
);

Notes and edge cases to watch for:

  • array_map can receive NULL for missing elements if arrays differ in length; trim both arrays to the shortest first with min(count($hours), count($minutes)) or explicitly validate sizes.
  • Cast inputs to integers and check ranges (0 <= minutes < 60, hours according to 12/24-hour needs) to avoid invalid times.
  • If times will be manipulated (add/subtract durations, sort by real time), create DateTime objects instead of formatted strings; that keeps operations reliable.

Further reading: see the PHP manual for array_map, sprintf, and DateTime for formatting and time arithmetic.

Recommended Answers

All 2 Replies

there probably is a simpler way but i made this i about 3 mins.

<?php

$hours = array(11,12,13,14);
$mins = array(30,30,30,30);

$count = count($hours);
$i = 0;
while ($i < $count) {
$time[] = $hours[$i] . ":" . $mins[$i];
$i++;
}

?>

all of the times are now stored in an array in the variable '$time'.

Hi,
Thanks 4 ur reply :) . i did it as below:
for($i = 0; $i < count($hours); $i++)
$time[$i] = $hours[$i] . ':' . $minutes[$i];
same way but with a for loop...

there probably is a simpler way but i made this i about 3 mins.

<?php

$hours = array(11,12,13,14);
$mins = array(30,30,30,30);

$count = count($hours);
$i = 0;
while ($i < $count) {
$time[] = $hours[$i] . ":" . $mins[$i];
$i++;
}

?>

all of the times are now stored in an array in the variable '$time'.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.