jimfog Posted January 17, 2012 Share Posted January 17, 2012 function calculate_items($cart){$items=0if(is_array($cart)){foreach ($cart as $isbn=>$qty){$items +=$qty;}}return $items;} Take a look at the above code-it is from a shopping cart application. The question is the following:Why the $items variable is declared with a value of zero? Can we just omit that? Link to comment Share on other sites More sharing options...
dsonesuk Posted January 17, 2012 Share Posted January 17, 2012 If you remove $items=0; and the if condition is false, then return is not going to know what $items refers to. Link to comment Share on other sites More sharing options...
Ingolme Posted January 17, 2012 Share Posted January 17, 2012 $items doesn't have a value if you don't set it. $items += $qty wouldn't mean anything if $items wasn't set to a value. You can't add a number to something that's not a number. Link to comment Share on other sites More sharing options...
birbal Posted January 17, 2012 Share Posted January 17, 2012 if $items is not defined it will be null after that if you use any arithmatic oprator it will be converted to ineteger. But this type casting NULL to integer result is undefined and should not be relied (if you run the code removing the declaration it will run well but with some notices) In other strict languages you must define ant variable before you use in case of php it does not matter much cause it will still run with some notices. but it is considered as secuirty faults so it must be avoided and must declare variables before you use. Link to comment Share on other sites More sharing options...
justsomeguy Posted January 17, 2012 Share Posted January 17, 2012 Add this to the top of your code (outside the function): error_reporting(E_ALL);ini_set('display_errors', 1); Then remove that line and see what happens. Link to comment Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.