I have an json-encoded array in my database which I like to add elements to. The json from the database looks like this:
{"1549006986":"a27f51b4dba8899c7a278465a873449a"}
Here is the code with which I want to add the element:
$tokenarray = json_decode($_SESSION['logintoken']);
$counttokens = count($tokenarray);
$newtoken = md5(mt_rand());
$datetime = $_SERVER['REQUEST_TIME'];
if ($counttokens < 6){
$tokenarray += [$datetime => $newtoken];
}
$tokenarrayjson = json_encode($tokenarray);
But this line
$tokenarray += [$datetime => $newtoken];
ends up in this error:
Fatal error: Uncaught Error: Unsupported operand types in **SITEURL** Stack trace: #0 {main} thrown in **SITEURL** on line
Can someone tell where im wrong here? From another post on this site, adding elements like this to an array should be valid from php version 5.4. I run on 7.2
Regards andreas
Your problem is your call to json_decode
. Because you have not passed the second parameter as true, it is returning an object, which you are then attempting to use as an array, causing the errors you are seeing. If you had put a print_r($tokenarray);
in your code after the json_decode
, you would have seen this:
stdClass Object (
[1549006986] => a27f51b4dba8899c7a278465a873449a
)
To fix it, change:
$tokenarray = json_decode($_SESSION['logintoken']);
to
$tokenarray = json_decode($_SESSION['logintoken'], true);
You also have a typo in your code,
newtoken = md5(mt_rand());
should be
$newtoken = md5(mt_rand());
Use this
$tokenarray[$datetime] = $newtoken;
I guess you have issue with your newtoken statement.
newtoken = md5(mt_rand());
You forgot to put $ before newtoken variable