By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
437,965 Members | 1,702 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 437,965 IT Pros & Developers. It's quick & easy.

Pass partial session variable name to function?

P: 22
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
Feb 27 '08 #1
Share this Question
Share on Google+
3 Replies


ronverdonk
Expert 2.5K+
P: 4,258
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='form1';

for ($i=1;$i<4;$i++) {
${$passed_form.'Var'.$i}=$_SESSION[$passed_form.'Var'.$i];
echo ${$passed_form.'Var'.$i};
echo '<br>';
}
?>[/php]Ronald
Feb 27 '08 #2

P: 22
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.variables.variable.php
Feb 27 '08 #3

ronverdonk
Expert 2.5K+
P: 4,258
Glad to be of help. See you next time.

Ronald
Feb 27 '08 #4

Post your reply

Sign in to post your reply or Sign up for a free account.