0

I have a cart class that returns the products in a users cart

cart.class.php

    public static function getItems()
    {
        if(!isset($_SESSION["cart"]["products"]))
        {
            return array(); 
        }
        else
        {
            return $_SESSION["cart"]["products"];
        }
    }

This is the code to get the cart and display it on the page

if($action == "getCart")
{       
    echo json_encode(Cart::getItems());

    exit;
}

When I'm testing the code on my localhost, it returns [] (Empty) but on my website it returns null. What have I done wrong?

3
  • have you declared session_start() anywhere? Commented Jan 5, 2014 at 13:09
  • Which function returns null? getItems() or the json_encode()? Commented Jan 5, 2014 at 13:09
  • Easy-one: you face a session problem. On website, u got a session but null value... on localhost, u have no session. Commented Jan 5, 2014 at 13:09

1 Answer 1

2

Try

return empty($_SESSION["cart"]["products"]) 
     ? array() 
     : $_SESSION["cart"]["products"];

That way, if $_SESSION["cart"]["products"] is null, you'll still get an empty array.

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

Comments

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.