How to create dynamic incrementing variable using "for" loop in php? like wise: $track_1,$track_2,$track_3,$track_4..... so on....
3 Answers
5 Comments
Lotus Notes
${...} is still a variable variable.
OM The Eternity
Y variable variables should be avoided?
OM The Eternity
What If I need the Value of variable previuos than the current variable? That is, ${'track_' . $i-1} can I do this?
o0'.
Why do you want to do that? Likely you should use an array.
Alix Axel
@Parth: You can but you should use it like this:
${'track_' . ($i - 1)} to keep the concatenation and the arithmetic clearly separated.<?php
for ($i = 1; $i <= 3; $i++) {
${"track_{$i}"} = 'this is track ' . $i; // use double quotes between braces
}
echo $track_1;
echo '<br />';
echo $track_3;
?>
This also works for nested vars:
<?php
class Tracks {
public function __construct() {
$this->track_1 = 'this is friend 1';
$this->track_2 = 'this is friend 2';
$this->track_3 = 'this is friend 3';
}
}
$tracks = new Tracks;
for ($i = 1; $i <= 3; $i++) {
echo $tracks->{"track_{$i}"};
echo '<br />';
}
?>