Jump to content

New to PHP and in need of help...


ketarn

Recommended Posts

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

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;
}
?>

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.