Jump to content

Redefining variable name within a loop


georage

Recommended Posts

I am trying to create a loop that redefines a variable name and assigns values to be used later.

 

In other programming languages I could use the counter itself as part of the variable name, by converting the loop INT to a STRING and concatenating that onto my generic variable name, BUT, I have not been able to figure out how to do this in PHP.

 

So, I am reduced to this kludge ... writing a separate code block for each iteration of the loop. This keeps me awake at night, as I know there has to be a better way.

 

For example, in the real world example below I would have thought I could get away with something like this:

 

$str=(string)$i; //make the loop counter a string

$headline . $str = $articleinfo['headline']; //create a new variable name for each loop!

 

I appreciate any assistance.

 

-- george

 

for($i=1; $i<=6; $i++) 
    	{
    	//fetch array    	   	
    	$articleinfo=mysql_fetch_array($resultarticles);	
    	
    	if($i==1)
    	{	
    	//headline
    	$headline1 = $articleinfo['headline']; 
    	   			
    	//author
    	$author1 = $articleinfo['author'];     			
    	
//article text
        $article1 = $articleinfo['article'];
    	}
      
       //repeat until blue in face       
       if($i==2) //etc
       {
       }

       //repeat until blue in face       
       if($i==2) //etc
       {
       }

       //repeat until blue in face       
       if($i==2) //etc
       {
       }

      //etc

}

 

 

 

 

Link to comment
Share on other sites

You could do it this way...

 

<pre>
<?php
for ($i=1; $i<=6; $i++) {
	$name = "name_$i";
	$$name = $i;
}
echo $name_1;
echo $name_2;
?>
</pre>

 

...but I recommend using an array:

 

<pre>
<?php
$name[] = null;
for ($i=1; $i<=6; $i++) {
	$name[] = $i;

}
print_r($name);
?>
</pre>

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.