[thelist] PHP + variables

Simon Willison cs1spw at bath.ac.uk
Fri Mar 15 15:59:01 CST 2002

Mark Joslyn wrote:

>Right now, I have 80+ if statements like this:
>$myAS400_Twinax = $AS400_Twinax;
>if ($myAS400_Twinax == "yes"){
>	$myAS400_Twinax = "\n  Twinax: YES";
>- one for each variable. There has to be a better way. Any suggestions?
There are two options for doing this more effectively off the top of my
head: The first is variable variables:

<input type="text" name="blah0">
<input type="text" name="blah1">
<input type="text" name="blah2">
<input type="text" name="blah3">

Then in your code:

for ($i = 0; $i < 4; $i++)
    $varvar = 'blah'.$i;
    $value = $$varvar;  // Two dollar signs because this is a variable
variable :)
    // Now do stuff with $value;

The second (better) option is to use array form fields:

<input type="text" name="blah[0]">
<input type="text" name="blah[1]">
<input type="text" name="blah[3]">
<input type="text" name="blah[4]">

When you post this form to a page, PHP will set up an array called $blah
with the items from the form.

The array method also works with named indexes:

<input type="text" name="blah[hi]">
<input type="text" name="blah[there]">
<input type="text" name="blah[this]">
<input type="text" name="blah[works]">



More information about the thelist mailing list