0

Am building a shopping cart and would like to append new items to a wishlist by adding them to a session but they shouldnt replace the existing items

This is what i have tried but returns an error of

[] operator not supported for strings

This is the code:

   public function addItem($value, (int)$id){
   if(isset($_SESSION[$value])){

        $_SESSION[$value][] = array();
        array_push($_SESSION[$value],array(
            'id'=>$id
        ));
        return true;
    }
}

The values of $value is a string

I have also followed on This yii link and also on This link but still am getting the same error

By doing it this way

   public function addItem($value, $id){
   if(isset($_SESSION[$value])){

        $_SESSION[$value] = array();
        array_push($_SESSION[$value],array(
            'id'=>$id
        ));
        return true;
    }
}

Adds the items but replaces whatever i had previously

WHAT DO I NEED TO CHANGE FOR IT TO WORK

2
  • what is $value? ur stock ? cause i would suggest u just use $_SESSION['items'][] = Array($id,$value); Commented Nov 23, 2016 at 9:13
  • 1
    “Adds the items but replaces whatever i had previously” – of course it does, if you assign a new empty array to $_SESSION[$value] every time. // $_SESSION is an array already, and you don’t need to initialize “sub-arrays” in PHP, it will create them automatically. So you can simply use $_SESSION[$value][] = 'new item'; to push new items into the array, the initialization with $_SESSION[$value] = array() is unnecessary. Commented Nov 23, 2016 at 9:44

1 Answer 1

1

You get this error when attempting to use the short array push syntax on a string. demo here.

$_SESSION[$value] is a string. so you cannot use something like $_SESSION[$value][]= 's'

So when the first time you use the $_SESSION[$value], make it an array. Not a string. Then you can use as $_SESSION[$value][]= 's';

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.