Jump to content


Photo

for loop help


  • Please log in to reply
3 replies to this topic

#1 ifreborn

ifreborn
  • New Members
  • Pip
  • Newbie
  • 7 posts

Posted 02 June 2006 - 02:40 AM

What am i doing wrong? how do i make $tom_ incriment?

<?php
$var = 10; 
$var1_ = "sam_";
for ($i = 1; $i <= "$var"; $i++)
{

$tom_$i = "$var1_$i";
print "tom_$i <br>";

}


######################################
#   What i would like to see print   #
######################################
/*
sam_1
sam_2
sam_3
sam_4
sam_5
sam_6
sam_7
sam_8
sam_9
sam_10
*/

?>


#2 kenrbnsn

kenrbnsn
  • Staff Alumni
  • Advanced Member
  • 8,235 posts
  • LocationHillsborough, NJ, USA

Posted 02 June 2006 - 02:59 AM

You want to use [a href=\"http://us2.php.net/manual/en/language.variables.variable.php\" target=\"_blank\"]variable variables[/a] here. Try this:
<?php
$var = 10;
$var1 = "sam_";
for ($i = 1; $i <= $var; $i++)
{

${"tom_$i"} = $var1 . $i;
print ${"tom_$i"} . "<br>";

}


######################################
#   What i would like to see print   #
######################################
/*
sam_1
sam_2
sam_3
sam_4
sam_5
sam_6
sam_7
sam_8
sam_9
sam_10
*/

?>

Ken

BTW, this is much easier if you use an array.

#3 poirot

poirot
  • Members
  • PipPipPip
  • Advanced Member
  • 646 posts
  • LocationAustin, TX

Posted 02 June 2006 - 03:06 AM

Exactly. During my first months using PHP (actually programming per se was new for me), I tried to do something like this, but believe me, arrays are a much better solution.
~ D Kuang

#4 ifreborn

ifreborn
  • New Members
  • Pip
  • Newbie
  • 7 posts

Posted 02 June 2006 - 03:06 AM

${"tom_$i"} is what i what i needed to learn thank you




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users