Search code examples
phparraysmultidimensional-arrayarray-push

AddToCart-System: array_push pushes on the "wrong level"?


I'm trying to make an "add to cart" function with this code:

if (empty($_SESSION['cart'])) {
    $_SESSION['cart'] = array(
        "id" => $_GET['id'],
        "size" => $_POST['size'],
        "count" => $_POST['count']
    );
} else {
    array_push($_SESSION['cart'], array(
        "id" => $_GET['id'],
        "size" => $_POST['size'],
        "count" => $_POST['count']
    ));
}

This is the output of print_r($_SESSION):

Array
(
    [cart] => Array
        (
            [id] => 1
            [size] => XS
            [count] => 1
            [0] => Array
                (
                    [id] => 2
                    [size] => XS
                    [count] => 1
                )
        )
)

You can see in the array what's wrong about my method pushing it. I want the new pushed content on the same "level" as the first entry above, if you know what I mean?


Solution

  • I'm not sure what do you mean by "the new pushed content on the same "level" as the first entry above", following scenario is impossible:

    $c = array(
               'id' => 1,
               'size' => 'X5',
               'count' => 1,
    
                // YOU CAN'T HAVE DUPLICATE KEYS IN YOUR ARRAY
               'id' => 2
    
      );
    

    so perhaps you should do array_push in both conditions (for the current example ofcourse), so you would get following structure:

    $c = array(
    
              0 => array(
                  'id' => 1,
                  'size' => 'X5',
                  'count' => 1,
               ),
    
              1 => array(
                   'id'=>2,
                   'size'=>'X3',
               ...
    
      );