View Full Version : Assigning value to auto increment variable

08-10-2012, 12:27 PM
hi all

first post and hopefully someone can help this has been doing my head in for last 24 hours , decide to appeal to the wonderweb to see if I can find someone much smarter than myself willing to point us in the right direction.

Any idea on how to assign value to a auto increment variable inside a loop .lets say for example

$letter = $i;

i want output in this way;


or any alternative to this?

Thanks in advance

08-10-2012, 01:23 PM
The real question is, "what is your goal, or purpose for doing this?"

Technically it can be done, but programming is based on "best principles",
making a script fast, efficient, and a non-burden for a processor.

What you might actually be thinking about is an array ...

$a[0] ... to .... $a[1000]

That would be 1001 unique values (variables) that are easily manipulated.

Tell us what your goal is, or what you're attempting to do.


08-10-2012, 03:20 PM

08-10-2012, 03:37 PM
sorry, i got it the wrong way round:

this is better:

$letters = array("","a","b","c","d","e");
$$letters[$i] = $i;
echo '<br>a = '.$a;
echo '<br>b = '.$b;
echo '<br>c = '.$c;
echo '<br>d = '.$d;
echo '<br>e = '.$e;

08-10-2012, 04:08 PM
Maybe you're talking about "variable variables"?

Should they be used?
In my opinion, never.


08-10-2012, 04:29 PM
I agree; I've yet to find a situation where variable variables are a requirement and there is always a way around them. They are more of a headache in keeping track of them.
Use arrays. If you can be clearer on the actual purpose, we can make better examples. Given what you have done here, a simple:

$aKeys = range("a", "e");
$aValues = range(1, count($aKeys));
$aResult = array_combine($aKeys, $aValues);

Would generate an associative array of the letters with the numbers.

08-10-2012, 05:19 PM
thanks to fou-lu for that as i have learnt about array_flip(); today lol :) (by googleing range())