Adding items to a php array without replacing the previous items
Get the solution ↓↓↓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
Answer
Solution:
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';
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: an exception occurred in the driver: could not find driver
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.