Tutorial :How to create dynamic incrementing variable using “for” loop in php?



Question:

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


Solution:1

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


Solution:2

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


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

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »