variable in a variable. Possible???

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
jtorral
Forum Newbie
Posts: 8
Joined: Mon Dec 29, 2008 7:49 pm

variable in a variable. Possible???

Post 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
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: variable in a variable. Possible???

Post by requinix »

Don't use quotes around variables when you don't need them.

Code: Select all

$cn = "cookie_name";
echo $_COOKIE[$cn];
jtorral
Forum Newbie
Posts: 8
Joined: Mon Dec 29, 2008 7:49 pm

Re: variable in a variable. Possible???

Post 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;
}
Last edited by Benjamin on Sat May 22, 2010 6:51 pm, edited 1 time in total.
Reason: Added [syntax=php] tags.
User avatar
Chalks
Forum Contributor
Posts: 447
Joined: Thu Jul 12, 2007 7:55 am
Location: Indiana

Re: variable in a variable. Possible???

Post 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).
Post Reply