1

How can I use loop (for, forEach, while etc.) to the following part of code. Here "tarray" is an array of 10 values. The part of the code :

$string = $tarray[0];
$datetime = strtotime($string);
$datetime1 = date("Y-m-d H:i:s", $datetime);
list($year, $month, $day, $hours, $minutes, $seconds) = explode('-', $datetime1);

$string = $tarray[1];
$datetimea = strtotime($stringa);
$datetime2 = date("Y-m-d H:i:s", $datetimea);
list($year, $month, $day, $hours, $minutes, $seconds) = explode('-', $datetime2);

I want to write this only once instead of declaring multiple variables.

1stthomas
  • 731
  • 2
  • 15
  • 22
Delegate
  • 65
  • 2
  • 10
  • what you want to do with this code... echo it..? Add in New array or what...Please elaborate... – GYaN Nov 10 '17 at 10:33
  • Show us the loop you have tried so far and tell us what doesn't work there – B001ᛦ Nov 10 '17 at 10:34
  • 1
    Possible duplicate of [Loop through an array php](https://stackoverflow.com/questions/4414623/loop-through-an-array-php) – 1stthomas Nov 10 '17 at 10:37
  • @GyandeepSharma I am repeating the same code again and again. So I want to convert it into a loop that will generate an array of "datetime" values – Delegate Nov 10 '17 at 10:42
  • @AlivetoDie I am repeating the same code again and again. So I want to convert it into a loop that will generate an array of "datetime" values – Delegate Nov 10 '17 at 10:43
  • @user8467658 can you please check once my answer – Alive to die - Anant Nov 10 '17 at 10:43
  • 1. It wont work with your date format. You need to use the character '-' that you use in the explode throughout like date("Y-m-d-H-i-s", $datetimea) else your list command will generate errors like it did when you tested it :) – TimBrownlaw Nov 10 '17 at 10:45

2 Answers2

2

I think you want like this:-

$date_array = [];
foreach($tarray as $tar){
    $datetime1 = date("Y-m-d-H-i-s",strtotime($tar));
    $date_array[] = array_combine(['year', 'month', 'day', 'hours', 'minutes', 'seconds'], explode('-', $datetime1));
}

Demo putput:- https://eval.in/897154

Note:- you can use list($year, $month, $day, $hours, $minutes, $seconds) = explode('-', $datetime1); also there without any issue.

Demo output:-https://eval.in/897156

Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98
0

Use foreach loop like that:

$arr = ['Hello', 'world', 'John'];
foreach($arr as $string) {
    echo $string;
}

So in your case:

foreach($tarray as $string) {
    $datetime = strtotime($string);
    $datetime1 = date("Y-m-d H:i:s", $datetime);
    list($year, $month, $day, $hours, $minutes, $seconds) = explode('-', $datetime1);
}
Roland Ruul
  • 1,172
  • 8
  • 15