products showing up twice in php array

Viewed 59

Please i need help, I am creating a shopping cart feature for a cake store. when i add a product it works but if i add it again it shows up as a 2nd array. How can i make sure a product just gets added once. i used in_array() function but i don't seem to get it right.

Here's my code

 <?php

session_start();
if(isset($_POST['add_to_cart']))
{
    // if the cart isn't opened
    if(!isset($_SESSION['cart']))
    {
        $_SESSION['cart'][0]=array('cakename'=>$_POST['cakename'],'cakeprice'=>$_POST['cakeprice'],'Quantity'=>1); 
        
        echo "<script>
        alert('Item Added');
        window.location.href='index.php';
        </script>";
    }
    // If the product already exists in the shopping cart
    elseif(in_array($_POST['cake_name'],$_SESSION['cart']))
    {
            echo "<script>
            alert('Item ALREADY Added');
            window.location.href='index.php';
            </script>";
            
    }
    else
    {
        $count= count($_SESSION['cart']);

        $_SESSION['cart'][$count]= array('cakename'=>$_POST['cakename'],'cakeprice'=>$_POST['cakeprice'],'Quantity'=>1);       
        
        echo "<script>
        alert('Item Added');
        window.location.href='index.php';
        </script>";
    }         
}
?>
1 Answers
// your session is a mutidimension array

// let session has the following values
$_SESSION['cart'] = [
    0 => ['cakename'=> 'cake1','cakeprice'=>'200.00', 'quantity'=>1],
    1 => ['cakename'=> 'cake2','cakeprice'=>'100.00', 'quantity'=>3],
    2 => ['cakename'=> 'cake3','cakeprice'=>'300.00', 'quantity'=>4]
];

// NOTE : I have skipped the validation / sanitizaion part of $_POST
$cakeName = $_POST['cakename'];
$cakePrice = $_POST['cakeprice'];

if(!isset($_SESSION['cart'])){
    $_SESSION['cart'] = [];
}
// empty array is false in <IF>
if($_SESSION['cart'] && ( $key = array_search($cakeName, array_column($_SESSION['cart'], 'cakename')) !== FALSE ){
    $_SESSION['cart'][$key]['quantity'] += 1;
} else {
    $_SESSION['cart'][] = ['cakename'=> $cakeName,'cakeprice'=>$cakePrice, 'quantity'=>1];
}

This might help!!

Related