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);
John Saunders
  • 160,644
  • 26
  • 247
  • 397
Max Underbed
  • 55
  • 1
  • 7

5 Answers5

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.

NendoTaka
  • 1,224
  • 8
  • 14
  • Thanks So much I'm low knowledge in php and I couldn't find a similar question on stackoverflow. Thanks. It WORKS!!! @nendotaka – Max Underbed May 24 '15 at 19:24
  • Please mark the question as answered so that people will know that you found a solution. – NendoTaka May 24 '15 at 19:29
  • I certainly would but it keeps saying "you can mark this as correct in XX minutes" – Max Underbed May 24 '15 at 19:30
  • 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. – NendoTaka May 25 '15 at 02:38
  • 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. – Max Underbed May 25 '15 at 13:47
  • You could make a class that has your values as public variables. http://php.net/manual/en/language.oop5.basic.php if you don't know how classes work. http://stackoverflow.com/questions/8612190/array-of-php-objects the first answer could be useful to you. – NendoTaka May 25 '15 at 14:56
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
);
mike.k
  • 3,277
  • 1
  • 12
  • 18
  • Just read it, the syntax for `array_push` is incorrect, it takes two+ arguments. First the target array, then the value(s) [array_push](http://php.net/manual/en/function.array-push.php). If you're trying to the key, just use the `=` directly. – mike.k May 25 '15 at 02:27
  • thanks for responding. I don't understand "use the = directly" I have it in there directly, don't I? – Max Underbed May 25 '15 at 02:38
  • `$_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. – mike.k May 25 '15 at 16:04
  • 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 – Max Underbed May 25 '15 at 21:58
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

Community
  • 1
  • 1
Falt4rm
  • 915
  • 6
  • 21
  • 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 – Max Underbed May 25 '15 at 13:44
  • 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. – Falt4rm May 25 '15 at 13:51
  • 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. – Max Underbed May 25 '15 at 14:00
  • 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 – Max Underbed May 25 '15 at 14:22
  • [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! – Falt4rm May 25 '15 at 14:32
  • My prices are not stored in a database that's the whole point of doing it like this instead of all through database. You didn't really help with my second question but thanks anyway for all the time you spend talking to me. God Bless. @Falt4rm – Max Underbed May 25 '15 at 14:39
  • Had 10min to cut - I did the basic - It's really weak compare to a mysqlDB but anyway. Feel free to upvote if it's what u needed. Peace! – Falt4rm May 25 '15 at 15:17
  • I'm really sorry for bothering you again and I don't count on you to answer but, what you wrote won't work. My idea was to add a `Quantity` varible to the each array. Is this possible. like `itemName -> eggs` `itemPrice -> 12.99` `itemAmount -> 3` Thanks. – Max Underbed May 25 '15 at 22:18
  • $_SESSION['cart']['item1']['itemPrice'] will return 12.5 & $_SESSION['cart']['item1']['quantity'] returns 5 . This works. But u can't use it like an Object. – Falt4rm May 25 '15 at 23:01
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();
}
Anuj
  • 1,474
  • 12
  • 23
0

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

Adrian Brown
  • 79
  • 1
  • 8