Can $_COOKIE ever have subarrays?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
Ambush Commander
DevNet Master
Posts: 3698
Joined: Mon Oct 25, 2004 9:29 pm
Location: New Jersey, US

Can $_COOKIE ever have subarrays?

Post by Ambush Commander »

It's common knowledge that:

Code: Select all

$_COOKIE
  cookiename => value
  cookiename => value
  ...
Is it ever possible that...

Code: Select all

$_COOKIE
  cookiename => array(value1, value2)
  ...
I'm asking this because I've made an iterative de-magic-quote function, but I don't want to call it unnecessarily because in non-array based inputs, it performs slightly worse.
User avatar
Weirdan
Moderator
Posts: 5978
Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine

Post by Weirdan »

Have you tried that? It's as easy as:

Code: Select all

if($_COOKIE) {
  var_dump($_COOKIE);
}

$_COOKIE['test'] = array('test', 'another one');
pointing your browser to the above page and hitting refresh
User avatar
wwwapu
Forum Contributor
Posts: 197
Joined: Wed Apr 07, 2004 11:57 am
Location: Turku, Finland

Post by wwwapu »

How about serialize()
User avatar
Weirdan
Moderator
Posts: 5978
Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine

Post by Weirdan »

PHP manual wrote: You may also set array cookies by using array notation in the cookie name. This has the effect of setting as many cookies as you have array elements, but when the cookie is received by your script, the values are all placed in an array with the cookie's name:

Example 3. setcookie() and arrays

Code: Select all

<?php
// set the cookies
setcookie("cookie[three]", "cookiethree");
setcookie("cookie[two]", "cookietwo");
setcookie("cookie[one]", "cookieone");

// after the page reloads, print them out
if (isset($_COOKIE['cookie'])) {
   foreach ($_COOKIE['cookie'] as $name => $value) {
       echo "$name : $value <br />\n";
   }
}
?>
which prints

Code: Select all

three : cookiethree
two : cookietwo
one : cookieone
User avatar
Ambush Commander
DevNet Master
Posts: 3698
Joined: Mon Oct 25, 2004 9:29 pm
Location: New Jersey, US

Post by Ambush Commander »

Meh. Should've checked the manual. Well, since I'm not going to use any cookies that do that, I'll effectively have no cookies like that... but it's a good thing to know.
Post Reply