EnglishAdam
EnglishAdam

Reputation: 1390

Changing variable Key values in Array with a Foreach loop

foreach( $notZeroValue as $cardSetPosition => $timesChosen){
    echo $groupValue;
    $notZeroValue[$cardSetPosition + ($groupValue*100)] = $notZeroValue[$cardSetPosition];
    unset ($notZeroValue[$cardSetPosition]);
}

Output is 0000 (correct because the $notZeroValue has four elements and for each one $groupValue = 0)

I know there must be a newbie error because changing *100 to +100 produces key values 101, 102, 103, 104.

print_r($notZeroValue); //output = array()

Upvotes: 1

Views: 150

Answers (1)

codaddict
codaddict

Reputation: 454970

With $groupValue equal to 0 you are getting correct results because

$notZeroValue[$cardSetPosition + ($groupValue*100)] = $notZeroValue[$cardSetPosition];

becomes

$notZeroValue[$cardSetPosition] = $notZeroValue[$cardSetPosition];

which is overwriting the array value with itself.

Next you delete the element from array.

So at the end the array will be empty.

But when you change * to + and $groupValue still at 0:

$notZeroValue[$cardSetPosition + ($groupValue+100)] = $notZeroValue[$cardSetPosition];

you'll not be overwriting the array values, instead you'll be creating new key/value pairs where keys are 100 more than old keys. Next you delete the old key/value from the array. So at the end you've 4 new key/value pairs.

Upvotes: 3

Related Questions