ianmc ianmc - 7 months ago 19
PHP Question

Using an array from a single cookie value as PHP array

I'm trying to use this cookie - current=["1","2","4"] - as a usable array in PHP.
At the moment I can echo these values, but can't use them as an array. How would I convert these values into a usable PHP array?

$currentUsers = $_COOKIE['current'];

echo $currentUsers;

print_r(array_values($currentUsers));

Answer
$array = explode(",",$currentUsers);
Var_dump($array);

Echo $array[0]; // 1
Echo $array[1]; // 2
Echo $array[2]; // 4

Edit: Not sure if the " is actually a part of the cookie values?
If it is you could use str_replace('"', '', $currentUsers); to remove the " from the values if you do it before the explode.

Edit2: as Ash pointed out I missed a part on the answer.
Here is the complete code:

$str = substr(str_replace('"', '', $currentUsers),1,-1);
$array = explode(",",$str);
Var_dump($array);

Echo $array[0]; // 1
Echo $array[1]; // 2
Echo $array[2]; // 4
Comments