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??

+3


source to share


5 answers


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');
}

      

+2


source


If you want to change the value in foreach, you need to access it by reference.



change foreach ($toReturn as $value)

toforeach ($toReturn as &$value)

+3


source


You need to change the value from the link:

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');
}

      

+3


source


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>

+1


source


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');
}

      

+1


source







All Articles