如何在php中使用“for”循环创建动态递增变量?

时间:2010-04-28 07:36:20

标签: php variables

如何在php中使用“for”循环创建动态递增变量? 像明智的一样:$ track_1,$ track_2,$ track_3,$ track_4 .....等......

3 个答案:

答案 0 :(得分:19)

使用parse_str()${'track_' . $i} = 'val';

答案 1 :(得分:3)

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

print("==" . $track_3);

答案 2 :(得分:0)

<?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;

?>


这也适用于嵌套变量:

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

?>