Reputation: 3
I have a long list of variables with a number at the end. For example address1 and I have all the way up top address14. I want to post these from a form but rather than type out $address1 = $_POST[address1] I would like to create a loop that loops round 14 times and changes the number at the end of address in both the variable name and in the $_POST section...
I am struggling to do this. I have a loop that creates the varaibles, but I keep getting errors as it isn't doing the $_POST bit.
Can someone please assist? Thank you.
This is what I currently have:
$x = 0;
while($x < 14) {
$address = "address" . $x;
$address = $$address;
$string = "<p>Address$x:" . $address[0] . "</p>";
echo $string;
$x = $x + 1;
}
Upvotes: 0
Views: 420
Reputation: 1096
You could also use the array syntax in your form :
<input type="text" name="address[1]" />
<input type="text" name="address[2]" />
<input type="text" name="address[3]" />
... up to 14
In PHP :
$address = $_POST['address'];
$address is now an array containing all the addresses
Upvotes: 0
Reputation: 616
Try this:
$addresses = array();
for( $x = 0; $x <= 14; $x++ )
{
$address_field = "address" . $x;
if( array_key_exists( $address_field, $_POST ) ) {
$addresses[$x] = $_POST[$address_field];
echo '<p>Address', $x, ': ', $addresses[$x], "</p>\n";
}
}
Upvotes: 0
Reputation: 441
why you don't do:
for ($i=0; $i < 14; $i++) {
$address[$i] = $_POST['address'.$i];
}
Upvotes: 2