0

I get the error Undefined index: item_total on the line $totals['item_total'] += (float)$quantity; I want $totals array to contain the $mycart summarized quantity data by Product.

$mycart = array();

$mycart[0]['product'] = 'ProductA'; 
$mycart[0]['quantity'] = 10; 

$mycart[1]['product'] = 'ProductA'; 
$mycart[1]['quantity'] = 4; 

$mycart[2]['product'] = 'ProductB'; 
$mycart[2]['quantity'] = 8; 

$mycart[3]['product'] = 'ProductB'; 
$mycart[3]['quantity'] = 8;  

$totals = array();
foreach ($mycart as $row) 
{
  $product = $row['product'];
  $quantity = $row['quantity'];
  $totals['item_total'] += (float)$quantity;
}

3 Answers 3

2

In php you can create an array index by $totals['item_total'] = value;. And you cannot use an array index in an expression if it has not been "initialized". What do you see when you write this statement out $totals['item_total'] += (float)$quantity; "long hand"? It is just a shortcut for $totals['item_total'] = $totals['item_total'] + (float)$quantity;. In the right-hand expression $totals['item_total'] has not been initialized, thus program gives "Undefined index" message.

Sign up to request clarification or add additional context in comments.

Comments

0

Your problem comes from using increment with an undefined variable

 $totals['item_total'] += (float)$quantity;

The reason for this is that increment does a read (to get the current value) of the variable, before increment it. Which makes sense because we need to know it's current value before we can add 1 to it.

Now because that variable is not defined, you get an error message Undefined index: item_total". Which also makes sense because we cannot get the value of something (read it) that has not been defined, because it doesn't exist yet.

To further illustrate this, we can manually increment without the += like this:

$totals['item_total'] = $totals['item_total'] + 1;

We should agree this is the same as $totals['item_total'] += 1 as they give the same value, but here you can see how we must reference the previous value of that variable, which is the same thing that += must do. And in the same line of reason we cannot read it if it's not defined.

 #Psudo for  $var = $var + 1
  write = read + 1

When simply assigning like this:

  $totals['item_total'] = 0;

There is no reading (of an undefined value, as we know what 0 is) that takes place, so PHP is fine with that variable not existing and just creates it. Some languages are not that forgiving. What I mean here is some languagues you would need to first define $totals as an array, and then add stuff to it. In PHP $totals doesn't even need to exist to do $totals['item_total'] = 0;

So as others noted you need to define it with a value of 0 before hand, that way when the read is done it will know it's 0 and you wont see the error.

$totals['item_total'] = 0;
 //or  $totals  = ['item_total' => 0];

foreach ($mycart as $row) 
{
  $product = $row['product'];
  $quantity = $row['quantity'];
  $totals['item_total'] += (float)$quantity;
}

echo $totals['item_total'];

Output

30

Sandbox

PHP is actually very forgiving about undefined variables, but in cases where it must first read that variable, it must be defined beforehand.

UPDATE

Based on this comment

I want it summed by product -- ProductA = 14 and ProductB = 16.

You can do it this way:

$mycart = array();

$mycart[0]['product'] = 'ProductA'; 
$mycart[0]['quantity'] = 10; 

$mycart[1]['product'] = 'ProductA'; 
$mycart[1]['quantity'] = 4; 

$mycart[2]['product'] = 'ProductB'; 
$mycart[2]['quantity'] = 8; 

$mycart[3]['product'] = 'ProductB'; 
$mycart[3]['quantity'] = 8;  

$totals = array();

foreach ($mycart as $row) 
{
    $key = $row['product'];

    if(!isset($totals[$key])){
        $totals[$key] = $row;
        // $totals[$key]  = $row['quantity']; //just [key=>quantity] no inner array
    }else{
        $totals[$key]['quantity'] += $row['quantity'];
       // $totals[$key]  += $row['quantity']; //just [key=>quantity] no inner array
    }
}

print_r($totals);

Output

Array
(
    [ProductA] => Array
        (
            [product] => ProductA
            [quantity] => 14
        )

    [ProductB] => Array
        (
            [product] => ProductB
            [quantity] => 16
        )

)

/*
   without the inner array
 Array
(
    [ProductA] => 14
    [ProductB] => 16
 )
*/

Sandbox

See my comments in the code on how to remove the inside array if you want just the Key and it's total quantity. If you do want the inner arrays but not the top level key (product), you can do this to remove those.

//after the loop
$totals = array_values($totals); //resets array keys to numbered keys

This will replace the ProductA and ProductB keys with 0 and 1.

Enjoy.

5 Comments

Making the suggested change made the error go away but I did not get the results I wanted. I need to update the $totals array with summarized quantity data by Product from $mycart. I thought the line "$totals['item_total'] += $quantity;" would update the $totals array with the cumulative quantity but nothing happens. Any help on how to get $totals to contain the summarized $mycart data?
When I run it I get 30 which is 10+4+8+8 Sandbox, if that is not correct what do you mean by cumulative.
Do you mean that you want to get the totals per item type, basically group the times together?
I want it summed by product -- ProductA = 14 and ProductB = 16.
The thing you missed here is you need to group them by the product, in PHP the array keys work exceptionally well for this (this is not true in a lot of languages), so we can take advantage of that.
0

Simply add this line right before foreach:

 $totals['item_total']=0;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.