NYCPHP Meetup

NYPHP.org

[nycphp-talk] accessing $_SESSION elements

Hans Zaunere hans at nyphp.org
Fri Oct 24 12:29:25 EDT 2003



Aaron Fischer wrote:

> Hi all,
> 
> I'm trying to avoid a bunch of if/then statements by looping through 
> $_SESSION.  I hit a roadblock that I can't seem to get around.  Here is 
> a simple piece of code which I think gets to the heart of the problem:
> 
> $begin=1;
> if(isset($_SESSION['$begin_fair_name']))
> {
>   echo "success";
> }

You need to isolate 'begin' as a variable; the above is looking for a variable named $begin_fair_name; that is, if there were double quotes around it.

One way to do this:

$begin=1;
if(isset($_SESSION["{$begin}_fair_name"]))
{
  echo 'success';
}

> Of course, this works:
> if(isset($_SESSION['$1_fair_name']))
> {
>   echo "success";
> }

But for the wrong reasons.

> BUT, I have between 1 and 10 fair_name fields (i.e. 1_fair_name, 
> 2_fair_name) coming from the form.  It would be much more efficient if I 
> can loop through and perform operations as opposed to a bunch of if/then 
> statements referring to specific fair_name fields.  Obviously the 
> problem is with using a variable inside the array and I haven't been 
> able to figure out how to work around it.

for( $i = 0; $i < 10; ++$i ) {

   if( isset($_SESSION["{$i}_fair_name"]) )
      echo 'success';

}

There are other ways to do it, too, for instance:

isset($_SESSION[$i.'_fair_name'])


H





More information about the talk mailing list