Jump to content

Using a variable as a session variable's name?


psyickphuk

Recommended Posts

Basically I have an array and I want go through it as follows:


$field_list array("text1", "text2", "etc");

for each ($field_list as $field)
   {
    if (!isset($_SESSION[$field])) { $_SESSION[$field] = null; }
   }

 

I tried with/without quotes but no joy. A bit of searching and I think I need to use variable variables but I'm not sure how to implement this? Any suggestions welcome ;)

 

 

<?php session_start();

$a=array("a","b","c","d");

foreach($a as $b){

$_SESSION['result'][]=$b;
}


$result=implode(' ',$_SESSION['result']);


echo $result;

?>

 

<?php session_start();

$a=array("a","b","c","d");

foreach($a as $b){

$_SESSION['result'][]=$b;
}

if($_SESSION['result'][]=''){

$_SESSION['result']=NULL;
}

$result=implode(' ',$_SESSION['result']);


echo $result;

?>

Basically I have an array and I want go through it as follows:


$field_list array("text1", "text2", "etc");

for each ($field_list as $field)
   {
    if (!isset($_SESSION[$field])) { $_SESSION[$field] = null; }
   }

 

I tried with/without quotes but no joy. A bit of searching and I think I need to use variable variables but I'm not sure how to implement this? Any suggestions welcome ;)

 

You're using the names correctly.  The problem is that you're checking to see if it's set, and if it's not, you're setting it to null...that's about as useful as setting a variable to 1 if it's 1....

 

also you forgot the = in the array assignment

 

$field_list = array("text1", "text2", "etc");

 

But I assume that was a typo...

 

Thanks redarrow I will try that later.

 

You're using the names correctly.  The problem is that you're checking to see if it's set, and if it's not, you're setting it to null...that's about as useful as setting a variable to 1 if it's 1....

 

Yes seems pointless to me too but if I don't null my variables then I get a variable undefined message when they're used.

 

You could argue not to do this and to their existence before usage but this seems to work and I only have to do it once.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.