Jump to content

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

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.