Pass partial session variable name to function?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • andrewteg
    New Member
    • Aug 2007
    • 22

    Pass partial session variable name to function?

    I have some variables in the session object that have the same naming convention like so:
    form1Var1, form1Var2, form1Var3...
    form2Var1, form2Var2, form2Var3...

    I need to use all of them in a function and would like to pass just "form1" to the function and then recreate the form1Var1, form1Var2, etc and read those values from the session object.

    Is there an easy way to recreate the variables that have a dynamic name? I looked at eval() but I'm not sure that would work for this.

    Thanks,
    Andrew
  • ronverdonk
    Recognized Expert Specialist
    • Jul 2006
    • 4259

    #2
    I am not quite sure what the 'session object' is, but I assume you mean the $_SESSION array.
    What you are looking for is using dynamic variable names. See the next sample and tell me if that is what you are looking for.[php]<?php
    session_start() ;

    $_SESSION['form1Var1']='myform1Var1';
    $_SESSION['form1Var2']='myform1Var2';
    $_SESSION['form1Var3']='myform1Var3';

    $passed_form='f orm1';

    for ($i=1;$i<4;$i++ ) {
    ${$passed_form. 'Var'.$i}=$_SES SION[$passed_form.'V ar'.$i];
    echo ${$passed_form. 'Var'.$i};
    echo '<br>';
    }
    ?>[/php]Ronald

    Comment

    • andrewteg
      New Member
      • Aug 2007
      • 22

      #3
      Thanks Ronald. That'll do the trick.

      Searching around for dynamic variables I found this official doc too for anyone else who is curious... http://www.php.net/manual/en/language.variab les.variable.ph p

      Comment

      • ronverdonk
        Recognized Expert Specialist
        • Jul 2006
        • 4259

        #4
        Glad to be of help. See you next time.

        Ronald

        Comment

        Working...