Sloth
08-10-2012, 11:27 AM
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="a";
for($i=1;$i<=5;$i++){
$letter = $i;
$letter++;
}
i want output in this way;
$a=1
$b=2
$c=3
$d=4
$e=5
or any alternative to this?
Thanks in advance
mlseim
08-10-2012, 12: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.
.
Arcticwarrio
08-10-2012, 02:37 PM
sorry, i got it the wrong way round:
this is better:
<?php
$letters = array("","a","b","c","d","e");
for($i=1;$i<=5;$i++){
$$letters[$i] = $i;
}
echo '<br>a = '.$a;
echo '<br>b = '.$b;
echo '<br>c = '.$c;
echo '<br>d = '.$d;
echo '<br>e = '.$e;
?>
mlseim
08-10-2012, 03:08 PM
Maybe you're talking about "variable variables"?
http://php.net/manual/en/language.variables.variable.php
Should they be used?
In my opinion, never.
.
Fou-Lu
08-10-2012, 03: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.
Arcticwarrio
08-10-2012, 04:19 PM
thanks to fou-lu for that as i have learnt about array_flip(); today lol :) (by googleing range())