chanw1 Posted July 2, 2010 Share Posted July 2, 2010 Hi Everyone I am stumped on a array problem and I was hoping someone could help Is there a way to add to an array value if a existing array key exists? I have 2 variables - ingredients and qty I'm looping through db results and I would like to build an array with a final total qty The array key will coming up more than once during the loop and I would like to add to that value if that array key exists. For example loop { test[$row['ingredient'] = $row['qty']; } results will be Array ( [Flour] => 11 [Milk] => 5 [sugar] => 2) Any help would be greatly appreciated. Thank You Link to comment https://forums.phpfreaks.com/topic/206491-add-to-array-please-help/ Share on other sites More sharing options...
Garethp Posted July 2, 2010 Share Posted July 2, 2010 foreach($row as $k=>$v) { $test[$k] = $v; } Link to comment https://forums.phpfreaks.com/topic/206491-add-to-array-please-help/#findComment-1080152 Share on other sites More sharing options...
Adam Posted July 2, 2010 Share Posted July 2, 2010 During your loop: if (array_key_exists($row['ingredient'], $ingredients)) { // not sure if you wanted to add (+) the quantity value here... $ingredients[$row['ingredient']] += $row['quantity']; // or just increment the value.. // $ingredients[$row['ingredient']]++; } else { // same here, if adding.. $ingredients[$row['ingredient']] = $row['quantity']; // if incrementing.. // $ingredients[$row['ingredient']] = 1; } Hopefully that made sense? Link to comment https://forums.phpfreaks.com/topic/206491-add-to-array-please-help/#findComment-1080160 Share on other sites More sharing options...
chanw1 Posted July 2, 2010 Author Share Posted July 2, 2010 Thank You So Much!!! Link to comment https://forums.phpfreaks.com/topic/206491-add-to-array-please-help/#findComment-1080224 Share on other sites More sharing options...
Adam Posted July 2, 2010 Share Posted July 2, 2010 No problem Link to comment https://forums.phpfreaks.com/topic/206491-add-to-array-please-help/#findComment-1080230 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.