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
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
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
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
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.