Reputation: 65
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.
Upvotes: 1
Views: 58
Reputation: 72289
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
Upvotes: 2
Reputation: 1242
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);
}
Upvotes: 0