Looking for a spot of advice here, hope someone can give me a hand.
I'm currently in the process of programming a shopping cart class for a site on which customers can purchase tickets for events. There are two main functions in the class: add() and modify() both of which affect the cart contents. If someone adds a new ticket to the cart it uses add() but if that ticket already is in the basket it uses modify() to update the quantity.
I have an exists() function to check if a cart exists first before processing either function.
PHP Code:
$cartid=$cart->exists($theitemid);
This will return the id of the cart, starting at 0 (it will be an array).
PHP Code:
if ($cartid){
$cart->modify($cartid,$theitemid,$quantity);
}else{
$cart->add($theitemid,$theitemdescription,$quantity,$price);
}
The above code will either add to or modify the cart depending on whether or not that item already exists. Because, say, someone might decide they want more after adding the first one.
HOWEVER....
If the $cartid is 0 (which means it's the first item in the cart) then the if clause "if ($cartid)" returns as 0 but I need it to recognise that as TRUE because that means it DOES EXIST in the cart (otherwise it would simply return nothing). I've also tried if($cartid!="") but the same thing happens: it implements add() because it interprets "0" as false.
Is there something I can do to prevent 0 coming back as false in this instance?
You need to use the strict comparison operator (=== or !==):
PHP Code:
if (0 == false) { // this will run } if (0 === false) { // this code will never run! }
This adds an additional check to the expression based on the types of the values being compared. Since 0 is an integer and false is boolean, the values are not of the same type and so will not evaluate true when compared.
The first rule of Tautology Club is the first rule of Tautology Club.
It's a little confusing because in my own php shopping cart I also have an exists() method in the class which accepts an input product_id.
My exists() method then returns true or false (1 or 0) depending on whether the product_id already exists in the cart. Product_id is a unique value in the products db table.
I would have thought that, assuming your $theitemid is also a unique value, then your exists() method only needs to return a value of true or false as well.
Am I misunderstanding something? because I don't understand why $cartid is an array
You need to use the strict comparison operator (=== or !==):
PHP Code:
if (0 == false) {
// this will run
}
if (0 === false) {
// this code will never run!
}
This adds an additional check to the expression based on the types of the values being compared. Since 0 is an integer and false is boolean, the values are not of the same type and so will not evaluate true when compared.
Bookmarks