[thelist] building a dynamic variable in php

shawn allen shawn at alterior.net
Mon Jan 13 12:05:01 CST 2003


quoth Tom Dell'Aringa:
> Hello,
>
> I'm building a 'mail to friend' list where I have 10 form fields
> labeled 1 through 10. In my php that processes the page, I thought
> instead of doing:
>
> $mail1 = $_POST["1"];
>
> I would instead run through a loop to do it:
>
> for($i = 1; $i <= 10; $i++) {
>
> then I would dynamically set each variable. This was what I tried:
>
> $mail . i = $_POST[i];

Try this:

    ${"mail" . $i} = $_POST[$i];

A much simpler method would be to use extract():

    extract($_POST, EXTR_PREFIX_ALL, 'mail');

Which would extract all of $_POST's keys into variables prefixed with
'mail' ($mail1...$mail10), and would eliminate the need for a loop. The
question is, why would you want to do this when you've already got the
data in an array? If you find yourself specifically referring to $mail1,
$mail2, etc. in your script, you might want to rethink your approach.

--
shawn allen
  mailto://shawn@alterior.net
  phone://415.577.3961
  http://alterior.net
  aim://shawnpallen




More information about the thelist mailing list