Tran
Tran

Reputation: 315

Use PHP to change multiple number to another number

In text, i have a lot of time number, then i want to change hour to another timezone (+6), example :

00:15 => 06:15

01:00 => 07:00

... and so on. I'm trying this :

$result = str_replace(
  array("00:","01:","02:","03:","04:","05:","06:","07:","08:","09:","10:","11:","12:","13:","14:","15:","16:","17:","18:","19:","20:","21:","22:","23:"),
    array("06:","07:","08:","09:","10:","11:","12:","13:","14:","15:","16:","17:","18:","19:","20:","21:","22:","23:","00:","01:","02:","03:","04:", "05:"),
    $text
);
 echo $result;

But 18: will replace with 04: because php replace 18: to 22: then continue replace 22: to 04:

How to solved this, thank you.

// Edit : To @user3414969 and @Medda86: $text is the data i'm get from another site, that mean i can not control the source, only way to do is replace

// Edit 2 : Here is content : http://bongdatv.net/test.php

// Edit 3: Please solve this problem with replace way, not calculation number way.

Upvotes: 0

Views: 190

Answers (4)

Shoaib Munir
Shoaib Munir

Reputation: 290

$time = array("00:","01:","02:","03:","04:","05:","06:","07:","08:","09:","10:","11:","12:","13:","14:","15:","16:","17:","18:","19:","20:","21:","22:","23:");

$required_time = array();
    
foreach($time as $t){
    $hour = $t."00"; // 00 appending 0 minites
    $hours_plus = 6; // adding 6 hours
    $required_time[] = date('H:', strtotime($hour)+($hours_plus*60*60));
}
echo "<pre>";
    print_r($required_time);
    echo "</pre>";

Upvotes: 1

devpro
devpro

Reputation: 16117

Try this:

$yourArr = array('00:15','01:00','00:30');
foreach ($yourArr as $key => $value) {
    $timestamp = strtotime($value) + 60*60*6; // add hours as per your need.
    $time = date('H:i', $timestamp);
    $newArr[] = $time;
}
echo "<pre>";
print_r($newArr);

Result is:

Array
(
    [0] => 06:15
    [1] => 07:00
    [2] => 06:30
)

Upvotes: 0

Amar Shukla
Amar Shukla

Reputation: 136

Optimal way is as suggested by Medda86
However, you can try upon this way

$array = ("00:","01:",....);
//Then you can loop over array and add the time 
for($i=0 ; $i < sizeof($array);$i++){
       $array[$i] = intval($array[$i]+6)%24;
       if($array[$i] < 10)
         $array[$i] = str_pad($array[$i],2,'0',STR_PAD_LEFT).':';
       else
         $array[$i] .= ':';
}

Upvotes: 0

Medda86
Medda86

Reputation: 1630

I think best is to use the timestamp format, add the time and get out the new time from that.

http://php.net/manual/en/function.time.php

Upvotes: 1

Related Questions