Jump to content

Incrementing variable name


benjam

Recommended Posts

How can I go about incrementing a variable name without using interim variables?

 

Example:

I have several variables called $foo_0, $foo_1, $foo_2, $foo_3, etc. and I would like to access them in a loop.

 

for ($i = 0; $i < $count; ++$i) {
    echo $foo_{$i}; // does not work, but would be the most elegant solution

    $name = 'foo_'.$i;
    echo ${$name}; // works but is not very elegant
}

 

Is the second solution the only way?  Or is there a variation of the first method that I'm just not seeing?

Link to comment
Share on other sites

Thanks Abra, that's what I was looking for.

 

And to all others, I am aware of arrays and understand they are easier/better in this particular situation, but the solution I was looking for is valid in other situations as well, not just looping over incremented variables.

Link to comment
Share on other sites

In whole my PHP career (which might not be all that long, but is not short either) I have never come across situation where I had to use variable variables. And for something like this... how can it be better than enumerated array is just above me.

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.