Replace array value with new
I have an array of array where I want to change the date format. I am trying to get it like below
foreach ($toReturn as $value) {
$start_date = new DateTime($value['start_date']);
$value['start_date'] = $start_date->format('m-d-Y');
$end_date = new DateTime($value['end_date']);
$value['end_date'] = $end_date->format('m-d-Y');
}
here the format changes, but it does not replace the array value with the new one. What for??
source to share
You must use the refrence operator &
to modify the original array, otherwise PHP will treat it as a local one that is different from the original, and changes to that local array will not be reflected in the original array.
foreach ($toReturn as &$value) {
$start_date = new DateTime($value['start_date']);
$value['start_date'] = $start_date->format('m-d-Y');
$end_date = new DateTime($value['end_date']);
$value['end_date'] = $end_date->format('m-d-Y');
}
source to share
Alternatively, if you don't want to use the Pass by Reference method, you can use that or even create a new variable.
foreach ($toReturn as $key => $value) {
$start_date = new DateTime($value['start_date']);
$toReturn[$key]['start_date'] = $start_date->format('m-d-Y');
$end_date = new DateTime($value['end_date']);
$toReturn[$key]['end_date'] = $end_date->format('m-d-Y');
}
Note . If you want to use reference pass, remember to undo ($ value) after the loop , which is not needed for this example .. p>
source to share
You can also use access $toReturn[$index]
foreach ($toReturn as $index => $value) {
$start_date = new DateTime($value['start_date']);
$toReturn[$index]['start_date'] = $start_date->format('m-d-Y');
$end_date = new DateTime($value['end_date']);
$toReturn[$index]['end_date'] = $end_date->format('m-d-Y');
}
source to share