Page 1 of 1

variable in a variable. Possible???

Posted: Sat May 22, 2010 6:19 pm
by jtorral
Normally,

I would check for a cookie something like this

$_COOKIE['cookie_name']

But how can I do this ...

$cn = "cookie_name";
$_COOKIE['$cn'];

I can't get it to work. Is there a special way of assigning a variable to a global predefined?

Thanks

Re: variable in a variable. Possible???

Posted: Sat May 22, 2010 6:38 pm
by requinix
Don't use quotes around variables when you don't need them.

Code: Select all

$cn = "cookie_name";
echo $_COOKIE[$cn];

Re: variable in a variable. Possible???

Posted: Sat May 22, 2010 6:50 pm
by jtorral
I tried that and it did not work. Here is what I have ...

i have javascript that sets a cookie when I click on a link.
I then call the function below from my php script to check the value of the cookie.

I am trying to use variable $div because I have 20 cookies withe the name xxx_div1 through xxx_div20 therefor I am trying to create the cookie name in the call so i can minimize code.

If i take the function below and replace $divcn with the actual cookie name it works as expected. If I use the variable, it always goes to the else.

Code: Select all

function checkdivsettings($div) {
   $divcn = "xxx_" . $div;
   if(isset($_COOKIE[$divcn])) {
      $div = $_COOKIE[$divcn];
   } else {
      $div = "block";
   }
   return $div;
}

Re: variable in a variable. Possible???

Posted: Sat May 22, 2010 10:17 pm
by Chalks
that's how you should do it. My guess is that it's not working because javascript is executed client-side (i.e. after the php has already finished running).