Jump to content

Add to Array - Please Help


chanw1

Recommended Posts

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

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?

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.