Reputation: 16204
How to create dynamic incrementing variable using "for" loop in php? like wise: $track_1,$track_2,$track_3,$track_4..... so on....
Upvotes: 2
Views: 12667
Reputation: 555
<?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 />';
}
?>
Upvotes: 0
Reputation: 24182
<?
for($i = 0; $i < 10; $i++) {
$name = "track_$i";
$$name = 'hello';
}
print("==" . $track_3);
Upvotes: 3