I have a cookie which I’m trying to split. The cookie is in this format:
key = val1,val2,val3 (where each value is separated by commas)
is there a way for me to split this in a loop so that I can directly access val3?
I’ve tried using the explode() function with no success.
for ($i = 0; $i < count($_COOKIE); $i++)
{
$ind = key($_COOKIE);
$data = $_COOKIE[$ind];
//I try and slit the cookie here
$cookie_temp = explode(",",$_COOKIE[$ind]);
//Here is where I wanted to display Val3 from the cookie
print $cookie_temp[2];
next($_COOKIE);
}
my code works fine but I then end up with all my Val3 in a large array. For example, my val3’s are numbers and they get put in an array. Can I split this even further?
Assuming you are looping because you have multiple comma-separated cookie key/value groups, use a
foreach()instead and withlist()you can retrieve the third value with a direct assignment.If you have only one cookie value to access, there is no need for the loop, and you can directly call
explode(",", $_COOKIE['key'])PHP 5.4 allows array dereferencing, whereby you can directly access the array element off of the
explode()call, but this won’t work in earlier PHP versions.