1

I 150 text fields in a form and I want to read the values when the form submitted. Do I have to write like below or there is any other short way...

$a1 = $_POST['a1']
$a2 = $_POST['a2']
$a3 = $_POST['a3']
$a4 = $_POST['a4']
$a5 = $_POST['a5']
----
----
----
$a150 = $_POST['a150']

I have printed all the text fields in form in using for loop in a form with name a1,a2,a3 and so on. I am wrinting as below but not workng

if (isset($_POST['save_exit']))
{

for ($j=1; $j<=150; $j++)
{
    ${a.$j} = $_POST['a'.$j];
}

    echo $a1;
}

but echo is not printing any value..

user2642907
  • 121
  • 1
  • 1
  • 11
  • 1
    Rather make your form input a list with the syntax `` so you'll get an array without workarounds. – mario Aug 06 '13 at 20:43
  • i would change the form so the fields where `name="xx[]"` the [] lets php create a nice array to loop through –  Aug 06 '13 at 20:43
  • See also [POSTing Form Fields with same Name Attribute](http://stackoverflow.com/q/2203430) – mario Aug 06 '13 at 20:44
  • possible duplicate of [moving a numbered amount of named items from one array into another](http://stackoverflow.com/questions/11942068/moving-a-numbered-amount-of-named-items-from-one-array-into-another) – mario Aug 06 '13 at 20:46

2 Answers2

2

change this line:

 ${a.$j} = $_POST['a'.$j];

to:

 ${"a".$j} = $_POST['a'.$j];

if you want to print, then just use:

echo ${"a".$j} = $_POST['a'.$j];
0

You can do some neat stuff with php. To do what you want, just use a loop like this:

$post_array[] = array();
for ($i = 0; $i < 150; $i++)
{
    if (isset($_POST["a$i"]))
    {
        $post_array[] = $_POST["a$i"];
    }
} 
if (count(post_array) < 5)
{
   echo "not validated";
}
Guybrush Threepwood
  • 3,333
  • 2
  • 19
  • 26