Question

Lets say I have the following associative array

$epl = array('Chelsea'=>array('gf'=>32,'ga'=>12,'pts'=>22),
             'ManCity'=>array('gf'=>43,'ga'=>20,'pts'=>18));

what if I want to update the pts data with some function where I would want to pull the current 22 points that Chelsea has and add 3 more points for another win and then store 25 back in that position. How would I do that? Can the following be done?

$newpts = $epl['Chelsea']['pts'] + 3;

$epl['Chelsea']['pts'] = $newpts;

Thanks for the help

Was it helpful?

Solution

You can simply just do this:

$epl['Chelsea']['pts'] += 3;

This will add 3 to the existing value and store it in the same place. This is the equivalent of writing this line:

$epl['Chelsea']['pts'] = $epl['Chelsea']['pts'] + 3;

The += and -= operators both work in-place, so += will add the value to the right to the variable on the left and store it in the variable on the left, and -= will subtract the value on the right from the variable on the left and store it in the variable on the left.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top