Jump to content

for loop help needed


essjay_d12

Recommended Posts

Hi,

 

I want to be able to add my $i to variables within a for loop (to creat multiple variables - the number of variables is dependant on the number of rows from a database - i.e. $final)

 

$final will be generated from a number of rows from a database - so will be unknown.

 

The below code didnt work - how do I go about adding a number to variables giving me the correct amount of variables

 

$i=1;

$final = 10;

 

for($i; $i>$final; $i++)

{

$name.$i = $_POST['name.$i'];

$number.$i = "$_POST['number.$i'];

}

echo $name2;

echo $name3;

 

Any ideas?

 

Cheers

 

S

 

Link to comment
https://forums.phpfreaks.com/topic/102118-for-loop-help-needed/
Share on other sites

If you want to do that, you should look into using arrays:

<?php
$final = 11;
$name = array();
for($i=1; $i<$final; $i++)
{
$name[$i] = $_POST['name'.$i];
$number[$i] = $_POST['number'.$i];
}
echo $name[2] . '<br>';
echo $name[3];
?>

 

Also, variables inside single quotes are not evaluated.

 

Ken

Link to comment
https://forums.phpfreaks.com/topic/102118-for-loop-help-needed/#findComment-522748
Share on other sites

Kinda right, but you still have the issue that you can't do this:

<?php
$_POST['name'.$i];
?>

I changed it to a while loop, but the principle is the same:

<?php
$name = array();
$number = array();

$i=1;
$final = 10;

while ($i < 10)
{
$name[$i] = $_POST['name'].$i;
/*print "part ".$i."done\n"; Edited to comment out error checking */
$number[$i] = $_POST['number'].$i;
++$i;
}
print_r($name);
print_r($number);
?>

Link to comment
https://forums.phpfreaks.com/topic/102118-for-loop-help-needed/#findComment-522759
Share on other sites

Yes, you can do:

<?php
$_POST['name'.$i];
?>

If you have a form with something like the following;

<input name="name1"><br>
<input name="name2"><br>
<input name="name3">

 

Please give an example of the form that would support your code.

 

Ken

Link to comment
https://forums.phpfreaks.com/topic/102118-for-loop-help-needed/#findComment-522776
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.