ketarn Posted October 2, 2007 Share Posted October 2, 2007 Hi there I'm new to PHP and while the site I am building is coming along nicely I'm stuck. My problem is, is there someway I can accomplish something like this: <?php $field1 = 0; $field2 = 0; $field3 = 0; $field4 = 0; $field5 = 0; ?> With a for loop? for($i=1;$i<=5;$i=$i+1) where the variable $i would replace the numerical portion of the $field variable name? Again I'm still pretty new to all of this so any help at all would be greatly appreciated. Thanks in advance. Link to comment https://forums.phpfreaks.com/topic/71529-new-to-php-and-in-need-of-help/ Share on other sites More sharing options...
d.shankar Posted October 2, 2007 Share Posted October 2, 2007 Yea you can buddy <?php for($i=1;$i<=5;$i++) { $field.$i=0; } for($i=1;$i<=5;$i++) { echo $field.$i; echo "<br>"; } ?> Link to comment https://forums.phpfreaks.com/topic/71529-new-to-php-and-in-need-of-help/#findComment-360112 Share on other sites More sharing options...
Rithiur Posted October 2, 2007 Share Posted October 2, 2007 This is very basic, and can be achieved using arrays. I would recommend reading about them. However, here is an example: <?php for ($i = 1; $i <= 5; $i++) { $field[$i] = 0; } ?> However, if you insist on not using arrays, it is also achievable with variable variables (though I would not recommend this approach): <?php for ($i = 1; $i <= 5; $i++) { $var = "field$i"; $$var = 0; } ?> Link to comment https://forums.phpfreaks.com/topic/71529-new-to-php-and-in-need-of-help/#findComment-360114 Share on other sites More sharing options...
Orio Posted October 2, 2007 Share Posted October 2, 2007 You can do that using variable-variables. <?php for($i=1; $i<=5; $i++) ${field.$i} = 0; echo $field1.$field2.$field3.$field4.$field5; //output= 00000 ?> But this method is not recommended. You should use arrays in this case. Orio. Link to comment https://forums.phpfreaks.com/topic/71529-new-to-php-and-in-need-of-help/#findComment-360115 Share on other sites More sharing options...
ketarn Posted October 2, 2007 Author Share Posted October 2, 2007 Okay guys thanks for the advice going to do some experimenting Link to comment https://forums.phpfreaks.com/topic/71529-new-to-php-and-in-need-of-help/#findComment-360121 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.