Hassan
Hassan

Reputation: 356

HTML form with loop and get data in an array

I need to solve this tricky question. I hope I will get solution from you.

I am creating a form which I must have to print from a PHP for loop like this:

<form method="get">
<?php
for ($i=1; $i <= 5 ; $i++) { 
    echo "Name: <input name='name[]' type='text' value=''/> Your Age: <input name='age[]' type='text' value=''/> Your Qualification: <input name='Qualification[]'  type='text' value=''/>";
    echo "<br/>";           
}   
?>
<input type="submit" name="submit" value="Submit">

This will give me 5 forms form each value.

What I need to do that when user put there data in fields.

This is how I want the data to show:

your name is xyz your age is 25 your qualification is aaaa.

Here is my code:

print_r ($name);
echo "<br />";
print_r ($age);
echo "<br />";
print_r ($qualification);
echo "<br />";

foreach($_GET['name'] as $key => $value){
if (!empty($value)) {
        $name[]="your name is :". $value;    
    }
}
foreach($_GET['age'] as $key => $value){
    if (!empty($value)) {
        $age[]=$value; 

    }
}
foreach($_GET['Qualification'] as $key => $value){
    if (!empty($value)) {
        $qualification[]=$value;  

    }
}
$yourname=implode(",",$name);
$yourage=implode(",",$age);
$yourqua=implode(",",$qualification);
echo $yourname . $yourage . $yourqua;
?>

And here is what I got:

your name is :xyz,your name is :abc25,14abc,dfg

It's like this but, I the need first line to give the output properly and then the next line, and then next line.

Upvotes: 0

Views: 1821

Answers (1)

BredeBS
BredeBS

Reputation: 198

replace your for with this

$array = array();
$int i = 0;
foreach($_GET['name'] as $key => $value){
    if (!empty($value)) {
        $array[$i]["name"] =$value; 
        $i++;
    }
}
$i=0;
foreach($_GET['age'] as $key => $value){
    if (!empty($value)) {
         $array[$i]["age"] =$value; 
         $i++;
    }
}
$i=0;
foreach($_GET['Qualification'] as $key => $value){
    if (!empty($value)) {
         $array[$i]["qualification"] =$value; 
        $i++;
    }
}
foreach($array as $key=>$value)
    echo $value["name"]." (".$value["age"].") = ".$value["qualification"]."<br/>";
}

Upvotes: 1

Related Questions