Php – Is it a good idea to modify the array keys in foreach

arrayPHP

Some times I need to modify an array key for example something like:

$temp = array();
foreach($arrayIWantToModify as $key => $value) {
    if($value % 2) == 0) {
        $temp['odd_' . $key] = $value;
    } else {
        $temp[$key] = $value;
    }
}

I always use a temp array to achieve that, but I had a memory problem when working on a project that had some big arrays. Of course the best solution is to increase the memory but, but i was just wondering is it so bad to just do it like:

foreach($arrayIWantToModify as $key => $value) {
    if(($value % 2) == 0) {
        $arrayIWantToModify['odd_' . $key] = $value;
        unset($arrayIWantToModify[$key]);
    }
}

It seems to work but I always saw it as a bad practice because you are changing an array you are iterating.

Best Answer

I would agree that this is not a good idea. Even if the language you're using defines what should happen in this situation (I don't know if PHP does; that's a question for StackOverflow) most people who see code like this would still have to look up whether or not it's defined behavior before they could have any confidence in it.

If the list of desired modifications is typically much smaller than the array being modified, I would always prefer using a temporary array to contain the desired modifications until the iterating is complete, just like your first example. If you're running out of memory doing that, that tells me you're modifying such a huge portion of the array that you'd be better off with a map operation (I believe PHP calls it array_map) that's designed to efficiently modify all elements without any risk of processing an element more or less than one time.