开发者

How to create dynamic incrementing variable using "for" loop in php?

How to create dynamic incrementing variable using "for" loop in开发者_JS百科 php? like wise: $track_1,$track_2,$track_3,$track_4..... so on....


Use parse_str() or ${'track_' . $i} = 'val';.


<?
for($i = 0; $i < 10; $i++) {
  $name = "track_$i";
  $$name = 'hello';
}

print("==" . $track_3);


<?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 />';
}

?>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜