How to pull information from an array and manipulate the data before storing it again in PHP

StackOverflow https://stackoverflow.com/questions/22340898

  •  13-06-2023
  •  | 
  •  

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

Était-ce utile?

La 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.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top