Jump to content

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
https://forums.phpfreaks.com/topic/207760-incrementing-variable-name/
Share on other sites

...but is not very elegant

 

Correct, arrays should be used when you have sets of related data.

 

Edit: Also see the post at the following link and the last post in the same thread - http://www.phpfreaks.com/forums/index.php/topic,303934.msg1437742.html#msg1437742

Don't shoot yourself in a foot. Use arrays instead:

http://php.net/manual/en/language.types.array.php

+1

 

Anytime you are needing to use variable variables (especially with an incrementing number), arrays should be used.  But to answer your question:

 

echo ${"foo_$i"};
//or
echo ${'foo_'.$i};

 

 

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.

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.

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.