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
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?

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.