1

I have a little script system. It replaces the array but I need it to add to the array. This is what I have:

$_SESSION['cart']=array(); // Declaring session array
array_push($_SESSION['cart'],'item1'); // Item added to cart

If after this I submit:

$_SESSION['cart']=array(); // Declaring session array
array_push($_SESSION['cart'],'item2'); // Item added to cart

It will contain item2 in array not item1 and item2.
How can I get it to do this?

So I changed up my code a bit and not when I push for example the code below twice it will overwrite the item. How can I make it add another one instead?

array_push($_SESSION['cart']['itemName'] = 13.99);

5 Answers 5

2

It seems that you are recreating the array on the second set of code meaning that you will delete everything already in the array. Did you try just array_push without the $_SESSION['cart']=array(); for the second set of code? If not try getting rid of that first line and see if it works.

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

6 Comments

Thanks So much I'm low knowledge in php and I couldn't find a similar question on stackoverflow. Thanks. It WORKS!!! @nendotaka
Please mark the question as answered so that people will know that you found a solution.
I certainly would but it keeps saying "you can mark this as correct in XX minutes"
Well as for you edit you are assigning the index itemName a value. So when you run this code again you are just re-assigning the value (writing over the old value). You need to use a different index name to store the new value.
is there a way that I could build in a quantity system. Have any ideas. I wouldn't even know how to start going about it. Because I would need a third value for each item. Thanks.
|
2

Use this syntax to append:

$_SESSION['cart'][] = 'item1';
$_SESSION['cart'][] = 'item2';

Edit:

// declare only if needed
if (!array_key_exists('cart', $_SESSION)) $_SESSION['cart'] = array();

// when adding an item at any future time once $_SESSION['cart'] exists:
$_SESSION['cart'][] = array(
     'itemName' => 'my item',
     'price' => 13.99
);

4 Comments

Just read it, the syntax for array_push is incorrect, it takes two+ arguments. First the target array, then the value(s) array_push. If you're trying to the key, just use the = directly.
thanks for responding. I don't understand "use the = directly" I have it in there directly, don't I?
$_SESSION['cart']['itemName'] = 13.99 does assignment, what is on the left gets set to what is on the right. And assuming it works, it will return a true. Then by the order of operations PHP will run array_push(true), which doesn't do anything.
ok thanks. If you would please look at my edit, is there a way to add it twice(or add another field quantity) thanks @mike.k
0

By calling this line every time :

$_SESSION['cart']=array();

You are cleaning out your cart session. If you wrap that in an if statement as well to check whether the array has already been instantiated, then you won't clean it out each time and you should be able to add to it as expected:

if (!isset($_SESSION['cart'])) {
    $_SESSION['cart']=array();
}

Comments

0

You are emptying your array before you add to it you declare $_SESSION['cart'] to equal a new empty array

Comments

0

U declared 2 times $_SESSION['cart']. Remove second declare and you should be good to go.

EDIT :

U don't use correct syntax for array_push.

PHP.net : array_push()

If i understood correctly - the index of key (numeric since array_push) bothers you.

U can bypass by using this code :

$_SESSION['cart'] = array();
$_SESSION['cart']['itemName'] = 12.50;

$_SESSION['cart'] = $_SESSION['cart'] + array("blabla" => 13.99);

print "<pre>";
print_r($_SESSION);
print "</pre>";

Result :

Array
(
[cart] => Array
    (
        [itemName] => 12.5
        [blabla] => 13.99
    )

)

LAST EDIT : (!?!)

 function set_item_price($itemName, $itemPrice)
{
    if(!isset($_SESSION['cart'][$itemName]['itemPrice']))
        $_SESSION['cart'][$itemName]['itemPrice'] = $itemPrice;

    else
        echo "Item Already exists \n <br>";
}

function add_to_cart($itemName, $quantity)
{
    if(!isset($_SESSION['cart'][$itemName]['quantity']))
        $_SESSION['cart'][$itemName]['quantity'] = $quantity;

    else
        $_SESSION['cart'][$itemName]['quantity'] += $quantity;
}




// Adding item1 - price 12.50
set_item_price("item1", 12.50);

// Adding item1 - quantity - 2 & 3
// OutPut will be 5
add_to_cart("item1", 2);
add_to_cart("item1", 3);

// Adding item3 - price 15.70
set_item_price("item3", 15.70);

// Adding item1 - quantity - 5
add_to_cart("item3", 5);


print "<pre>";
print_r($_SESSION);
print "</pre>";


?>

RESULT :

Array
(
[cart] => Array
    (
        [item1] => Array
            (
                [itemPrice] => 12.5
                [quantity] => 5
            )

        [item3] => Array
            (
                [itemPrice] => 15.7
                [quantity] => 5
            )

    )

)

Otherwise check on this thread :

Stackoverflow : how-to-push-both-value-and-key-into-array-php

9 Comments

Hey thanks for the update it won't help. I put it into my system it does exactly the same thing as my code. When first activated adds it to array(cart) then any time after that it just doesn't change anything. You have any idea instead of putting two of the same item to build in a quantity feature how could I do that? Thanks. @Falt4rm
First of all u won't be able to get 2 keys with the same name into an array. How could u found out which one u want after that? From what i understand u'll have to do another lvl in order to use your add function on the same item - Ex : [cart][itemName][0] for first add then [cart][itemName][1] for second one.
yeah, but if I just add it like that it messes up the code. Is there a trick to add a third variable to one array? Thanks.
Thanks for the link. But its not helpful it's exactly what I'm using. to get two things in one array. I was wondering if I could get three. This is what I have [itemName][itemPrice] I would like to have '[itemName][itemPrice][itemQuantity +1]' if possible
[itemName][itemPrice][itemQuantity +1] make no sense since the price is stored in your database (or should be). [itemName] => itemQuantity then query the ItemPrice from ur db is the only correct way to process. Can't justify Adding one more dimension (with itemPrice). Peace!
|

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.