Dino55
Dino55

Reputation: 431

"Notice: Undefined variable" error and foreach loop

Can someone please explain to me why I get "Notice: Undefined variable" for variable $subtotal in the 2nd code snippet but NOT in the 1st code snippet ? What's the difference between them? Are they consider local variables?

Also, exactly what is the variable type (Global, Superglobal.. etc) of $cartKey and $cartItem in the foreach loop? How come I didn't need to define/declare them?

switch( $_SESSION['shippingMethod'] )
{
  case "Air": 
             $shipping = $subtotal * 0.1;
             break;
}

and

foreach( $cart as $cartKey => $cartItem )
{
    $subtotal += $cartItem['total'];
}

Thank you very much in helping.

Upvotes: 1

Views: 2087

Answers (2)

Lawrence Cherone
Lawrence Cherone

Reputation: 46602

Basically the error is saying your using $subtotal variable before its set, or in your case your increasing a value to it before its been set:

$subtotal=0;
foreach( $cart as $cartKey => $cartItem )
{
    $subtotal += $cartItem['total'];
}

Edit: If $subtotal is set perhaps due to some other code setting it or its not set then a check should be made, or you should set it at the start of your script:

$subtotal=(isset($subtotal))?$subtotal:0;
foreach( $cart as $cartKey => $cartItem )
{
    $subtotal += $cartItem['total'];
}

When developing any script its always a good idea to have error_reporting(E_ALL) to give you every error in your code, it helps you learn in the long run. Once you see a few Notice Undefined messages your change the way you code & check for variables. Then when the script is ready for release turn E_ALL to 0

Upvotes: 7

prodigitalson
prodigitalson

Reputation: 60413

Apprently $subtotal doesnt exist yet in the area where the loop is. Since you are using += you are getting this error beacuse you are essentially saying:

$subtotal = $subtotal + $cartItem['total']

in the cases of $cartKey and $cartItem you did define them... they are part of the loop structure you create them from the current key and value of the array item - "copying" them into the current scope from the array. Eg. by doing $cartKey => $cartItem you defined those variables.

Upvotes: 3

Related Questions