• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 379
  • Last Modified:

Adding to, or Editing a shopping cart array

I need help with determining if an item is in my Cart array:  ($_SESSION['cart'])
   If not, add it to the Cart array and increment Quantity
else
   just increment Quantity
------------------------------------------------------------------------------------

On the Shopping form:
I have 13 hard-coded items, each with an input button  that POST the selection when the user clicks it:
    <td><input type="image" src="images/CartAdd1.gif" NAME="Brown_Shoes" VALUE="ADD"></a></td>
    <td><input type="image" src="images/CartAdd1.gif" NAME="Red_Hat" VALUE="ADD"></a></td>

On The Cart form:
I can capture the NAME of the product the user wants to add just fine:
    if (@$_POST['Brown_Shoes'] == 'ADD') {
    echo "<p>Don't wear Brown_Shoes with a blue suit</p>";
    }
    elseif (@$_POST['Red_Hat'] == 'ADD') {
    echo "<p>You'll look marvelous in a Red_Hat</p>";
    }

I have an empty Cart array (in a Session), but I don't have the array formatted, only referenced as a session array()
I have a populated Products array - from the products.php file:    (required)
    <?php
    $products = array(
        'Brown_Shoes' => array('price' => 18, 'quantity' => 0),
        'Red_Hat' => array('price' => 18, 'quantity' => 0),
        'Green_Sleeves' => array('price' => 22, 'quantity' => 0),
.... you get the idea
        );
    ?>
(Notice the NAME being POSTED is the same as the Key in the $products array)

Ok, so for the money, can you please tell me how to add the selected product and/or increment it's Quantity?
(I already have code that echoes the records in the Cart array to a table on the Cart page)
(I already have code that Updates the Cart array if the user changes the quantity of an item, or clears the Cart array)

All I need help with is how to determine if an item is in my Cart array:  ($_SESSION['cart'])
   If not, add it to the Cart array and increment Quantity
else
  (If so), just increment Quantity

Thanks very much,
David



0
DavidWare
Asked:
DavidWare
  • 15
  • 14
1 Solution
 
nizsmoDeveloperCommented:
This can easily be done by searching through the array. Example code below, hope this helps demostrate how it could be done.
<?php
	// Example, you have a product name here
	$product_name = "Brown_Shoes";
	
	// then to check if Brown_Shoes is in the array already??
	$position = array_search($_SESSION["cart"]);
	
	if(!$position)
	{
		// Product not found in the array! so add it to the array here!
	}
	else 
	{
		// Product found in the array already, so increment it using something like $_SESSION["cart"][$position] to access the array value
	}
?>

Open in new window

0
 
DavidWareAuthor Commented:
Hello
Thanks for replying.
I don't know the "add" syntax, so here's what I tried:
---------------------------  start code  ---------------------------------------
//search for $product_name in the array
$position = array_search($_SESSION["cart"]);
if( $position == false ) {
    // Product not found in the array! so add it to the array here!
    array_push( $_SESSION['cart'], $product_name => 1 );

} else {
    // Product found in the array already, so increment it using something like
    $_SESSION['cart'][$position] = ( $product_name => $_SESSION['cart']['quantity']++ )
}

----------------------  end code  ***********************

I'm getting an error on my line
array_push( $_SESSION['cart'], $product_name => 1 );

Parse error: syntax error, unexpected T_DOUBLE_ARROW in /var/www/sites........

Any recommendations?

Thanks!
David
0
 
DavidWareAuthor Commented:
I instantiated the array in the website's home page in 2 ways, both get the same error:
<?php
session_start();
$_SESSION['cart'] = array();       //  <-----
?>

and

<?php
session_start();
$_SESSION['cart'] = array(array());       //  <-----
?>
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
nizsmoDeveloperCommented:
Sorry found some errors with my code (and yours) so modified it slightly, this should work much better, if it works at all :P
<?php
	$product_name = "Brown_Shoes";
	//search for $product_name in the array
	if( array_key_exists($product_name, $_SESSION["cart"]) == false ) {
	    // Product not found in the array! so add it to the array here and set the quantity
	    $_SESSION['cart'][$product_name] = 1;
	
	} else {
	    // Product found in the array already, so increment it using something like
	    $_SESSION['cart'][$product_name] = $_SESSION['cart'][$product_name]+1;
	}
?>

Open in new window

0
 
DavidWareAuthor Commented:
Well, I see that it's inserting something into the array, but it seems as though only 1 record is going in and then incrementing, no matter which product I select.
Other errors (in the reporting code from my book) are preventing the form from loading fully, so it's a little hard to tell.

Could you please explain how I reference the elements/positions in this embedded array?

For instance, your line of code:
$_SESSION['cart'][$product_name] = 1
doesn't seem to reference the 'quantity' index, it only seems to reference the Key.
So how does PHP know whether you're talking about 'price' or 'quantity'?

My Cart array should be a subset of my $products array
    $products = array(
        'Brown_Shoes' => array('price' => 18, 'quantity' => 0),
        'Red_Hat' => array('price' => 18, 'quantity' => 0),
        'Green_Sleeves' => array('price' => 22, 'quantity' => 0),
.... you get the idea
        );

with Key => (Key => Value) as Value    (does that make sense?

In a BASIC array, I'd say something like
$_SESSION['cart'][$product_name] [2] = 1

but the "array of arrays" paradigm is hard to master.

Thanks again!!!
0
 
DavidWareAuthor Commented:
Yes, one error says:
Notice: Undefined offset: 0 in /var/www/sites/....

The offending line is looping through the Cart array and searching for a corresponding $product[$id]

So it looks like your example isn't addressing the "embedded-ness" of the Cart array.

Am I on the right track?
0
 
nizsmoDeveloperCommented:
not sure, as i am still unfamiliar with your code. are you able to post that segment of the code?
0
 
nizsmoDeveloperCommented:
I will try and explain this as best as i can, not sure why it is not working properly but as you said it is hard to tell without knowing the code, so even harder for me!

$_SESSION["cart"] is an array.

Now I am not sure of the format that this 'cart' array is suppose to be in, but what i did in the above code was:

to put the product name ($product_name) as the KEY of the array, thus it is enclosed with [ ] brackets. The actual value in the array is then the quantity, therefore i put = 1.

So the array would look something like this (ideally in my mind):

Array Key    QTY
product 1      1
product 2       3
product 3        5
product 4       2
etc...

Hope you understand what I am trying to accomplish.
0
 
DavidWareAuthor Commented:
Hi nizsmo,
Thank you so much for sticking with me.

My Cart array should be a subset of my $products array
    $products = array(
        'Brown_Shoes' => array('price' => 18, 'quantity' => 0),
        'Red_Hat' => array('price' => 18, 'quantity' => 0),
        'Green_Sleeves' => array('price' => 22, 'quantity' => 0),
.... you get the idea
        );

Does that help?
0
 
nizsmoDeveloperCommented:
Yes kind of does. I have modified it a little bit more now, with a sub-array which contains the price and the quantity. Hope you get what i am doing.
<?php
        $product_name = "Brown_Shoes";
        $product_price = 18;
        //search for $product_name in the array
        if( array_key_exists($product_name, $_SESSION["cart"]) == false ) {
            // Product not found in the array! so add it to the array here and set the quantity
            $_SESSION['cart'][$product_name] = array('price' => $product_price, 'quantity' => 1);
        
        } else {
            // Product found in the array already, so increment it using something like
            $_SESSION['cart'][$product_name]['quantity'] = $_SESSION['cart'][$product_name]['quantity']+1;
        }
?>

Open in new window

0
 
DavidWareAuthor Commented:
Yes, brilliant!  I see where you're going.

So, replacing the "hard-coded' values:
        $product_name = "Brown_Shoes";
        $product_price = 18;

I'm replacing $product_name with what's coming in on the POST

I'll need to find the corresponding $products() ['price] using the $Key (which is the same as $product_name)

This is what I tried:
$product_price = $products[$product_name]['price'];

but it errors:
Notice: Undefined index: in /var/www/sites/...

So I think I'm VERY close, if I can just get the correct syntax for pulling the current product's Price from the $products() array....

Please? (I know it's getting late where you are)
0
 
nizsmoDeveloperCommented:
How are you getting the product name? you should be able to use the same method for getting the product price.

also can you try this:
print_r($products,true);

and let me know what the output is?
0
 
nizsmoDeveloperCommented:
and yes, very late. will need to go soon :P
0
 
DavidWareAuthor Commented:
I'm getting the product name in the POST from the previous (shopping) FORM

in this form, my code determines which product the user selected like this...

if (@$_POST['Brown_Shoes'] == 'ADD') { $product_name == "Brown_Shoese"; }
elseif (@$_POST['Red_Hat'] == 'ADD') { $product_name == "Red_Hat"; }
elseif (@$_POST['Green_Sleeves'] == 'ADD') { $product_name == "Green_Sleeves"; }

And this echoes correctly.  What's coming in onthe POST is exactly the same as the Key of the $products array

The $products array is being populated in a "required" include that looks like this;
<?php
// Just an include file with our product data.  Eventually we'll read
// this information in from a database

$products = array(
    'Brown_Shoes' => array('price' => 18, 'quantity' => 0),
    'Red_Hat' => array('price' => 18, 'quantity' => 0),
    'Green_Sleeves' => array('price' => 22, 'quantity' => 0),
    );
?>

(of course there are 13 items, and the names have been shortened for my question)

I can't get your code to print anything.

I gutted the part of the code that's doing things with the Cart array and left all the rest (the part that gathers everyting) so there are no errors, but nothing prints besides the empty table and the labels.

0
 
nizsmoDeveloperCommented:
sorry, how about:

print_r($products);

let me know the output, thanks.
0
 
nizsmoDeveloperCommented:
The below code, i took a segment of your posted code, and tested, works perfectly. not sure why it is not working for you?
<?php
	$products = array(
    'Brown_Shoes' => array('price' => 18, 'quantity' => 0),
    'Red_Hat' => array('price' => 18, 'quantity' => 0),
    'Green_Sleeves' => array('price' => 22, 'quantity' => 0)
    );
    
    $product_name = "Red_Hat";
    $product_price = $products[$product_name]['price'];
    echo $product_price;
// This echo's 18! so expected and working perfectly!
 ?>

Open in new window

0
 
DavidWareAuthor Commented:
Here's the output (I told you I shortened the names...)


Array ( [Bowl_in_Green_glaze] => Array ( [price] => 18 [quantity] => 0 ) [Bowl_in_Cobalt_glaze] => Array ( [price] => 18 [quantity] => 0 ) [Lunch_Plate] => Array ( [price] => 22 [quantity] => 0 ) [Dinner_Plate] => Array ( [price] => 30 [quantity] => 0 ) [Spiral_Mug_in_Green] => Array ( [price] => 20 [quantity] => 0 ) [Mug_Spiral_in_Cobalt] => Array ( [price] => 20 [quantity] => 0 ) [Mug_Spiral_in_Periwinkle] => Array ( [price] => 20 [quantity] => 0 ) [The_Bup_in_Periwinkle] => Array ( [price] => 22 [quantity] => 0 ) [The_Bup_in_Green] => Array ( [price] => 22 [quantity] => 0 ) [Double_Happiness_Bowl] => Array ( [price] => 60 [quantity] => 0 ) [Double_Happiness_Bowl_with_dragonflies] => Array ( [price] => 120 [quantity] => 0 ) [Hosta_Leaf_Tray_in_Red_stoneware] => Array ( [price] => 40 [quantity] => 0 ) [Hosta_Leaf_Tray_in_White_stoneware] => Array ( [price] => 40 [quantity] => 0 ) )
0
 
nizsmoDeveloperCommented:
The array is in the format i expected. can you somehow copy and modify from my code above and see if it will work for you? not sure what you are missing/doing wrong.
0
 
DavidWareAuthor Commented:
So when the user select an item (on the shopping page, in a FORM), this is the ADD button code:

<td><input type="image" src="images/images_CartAdd1.gif" NAME="Bowl_in_Green_glaze" VALUE="ADD"></a></td>


then, in the cart page, this is the code that determines what product he selected:

if (@$_POST['Bowl_in_Green_glaze'] == 'ADD') { $product_name == "Bowl_in_Green_glaze"; }
elseif (@$_POST['Bowl_in_Cobalt_glaze'] == 'ADD') { $product_name == "Bowl_in_Cobalt_glaze"; }
elseif (@$_POST['Lunch_Plate'] == 'ADD') { $product_name == "Lunch_Plate"; }
elseif (@$_POST['Dinner_Plate'] == 'ADD') { $product_name == "Dinner_Plate"; }
elseif (@$_POST['Spiral_Mug_in_Green'] == 'ADD') { $product_name == "Spiral_Mug_in_Green"; }
elseif (@$_POST['Mug_Spiral_in_Cobalt'] == 'ADD') { $product_name == "Mug_Spiral_in_Cobalt"; }
elseif (@$_POST['Mug_Spiral_in_Periwinkle'] == 'ADD') { $product_name == "Mug_Spiral_in_Periwinkle"; }
elseif (@$_POST['The_Bup_in_Periwinkle'] == 'ADD') { $product_name == "The_Bup_in_Periwinkle"; }
elseif (@$_POST['The_Bup_in_Green'] == 'ADD') { $product_name == "The_Bup_in_Green"; }
elseif (@$_POST['Double_Happiness_Bowl'] == 'ADD') { $product_name == "Double_Happiness_Bowl"; }
elseif (@$_POST['Double_Happiness_Bowl_with_dragonflies'] == 'ADD') { $product_name == "Double_Happiness_Bowl_with_dragonflies"; }
elseif (@$_POST['Hosta_Leaf_Tray_in_Red_stoneware'] == 'ADD') { $product_name == "Hosta_Leaf_Tray_in_Red_stoneware"; }
elseif (@$_POST['Hosta_Leaf_Tray_in_White_stoneware'] == 'ADD') { $product_name == "Hosta_Leaf_Tray_in_White_stoneware"; }

which brings in the $product_name

which is exactly the same as the $products() $Key
0
 
nizsmoDeveloperCommented:
sorry it is getting very late, so need to go for now. pls post any progress or proiblms here and i will surely come and help you once i am back!
:)

good luck!
0
 
DavidWareAuthor Commented:
Here is your code, with my replacement of the "hard-coded" value for $product_price
($product_name was already acquired)

$product_price = $products[$product_name]['price'];     <------  THIS IS MY PROBLEM!!!!!!!!!

        //search for $product_name in the array
        if( array_key_exists($product_name, $_SESSION["cart"]) == false ) {
            // Product not found in the array! so add it to the array here and set the quantity
            $_SESSION['cart'][$product_name] = array('price' => $product_price, 'quantity' => 1);
       
        } else {
            // Product found in the array already, so increment it using something like
            $_SESSION['cart'][$product_name]['quantity'] = $_SESSION['cart'][$product_name]['quantity']+1;
        }
0
 
nizsmoDeveloperCommented:
hi i'm back :)

does the below script work kfor you (just to test it out, so that it is not something wrong with your system.)

$product_price = $products[$product_name]['price'];     <------  THIS IS MY PROBLEM!!!!!!!!!

that seriously looks ok, how about trying to hardcode the $product_name see if it works?
$product_price = $products["Red_Hat"]['price'];
<?php
        $products = array(
    'Brown_Shoes' => array('price' => 18, 'quantity' => 0),
    'Red_Hat' => array('price' => 18, 'quantity' => 0),
    'Green_Sleeves' => array('price' => 22, 'quantity' => 0)
    );
    
    $product_name = "Red_Hat";
    $product_price = $products[$product_name]['price'];
    echo $product_price;
// This echo's 18! so expected and working perfectly!
 ?>

Open in new window

0
 
DavidWareAuthor Commented:
Thank you so much, nizsmo, for giving me that confirmation.
I have put an email in to my host's mechanic.

I am very grateful for your generously giving me your time and expertise!
David
0
 
DavidWareAuthor Commented:
Absolutely spectacular solution with excellent followup!
0
 
nizsmoDeveloperCommented:
no problem, hope i have helped in some way! Goodluck!
0
 
DavidWareAuthor Commented:
Well, the problem was indeed syntactic.  I was using == instead of =

$product_name == "Brown_Shoes"

instead of

$product_name = "Brown_Shoes"

if (@$_POST['Brown_Shoes'] == 'ADD') { $product_name == "Brown_Shoes"; }
elseif (@$_POST['Red_Hat'] == 'ADD') { $product_name == "Red_Hat"; }
elseif (@$_POST['Green_Sleeves'] == 'ADD') { $product_name == "Green_Sleeves"; }

So $product_name was never getting a value.

My head hurts!

0
 
nizsmoDeveloperCommented:
ahhhh and i didn't spot it! well done on your part :)
0
 
DavidWareAuthor Commented:
Ok, I've got 65 more points, so I'm going to post one more question, then I'll know everything there is to know about PHP ...... I'll have to   :)
0
 
nizsmoDeveloperCommented:
hahaha :)
0

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

  • 15
  • 14
Tackle projects and never again get stuck behind a technical roadblock.
Join Now