2

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

1
  • 7
    I hope you are not trying to emulate arrays ;-) Commented Apr 28, 2010 at 7:51

3 Answers 3

19

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

Sign up to request clarification or add additional context in comments.

5 Comments

${...} is still a variable variable.
Y variable variables should be avoided?
What If I need the Value of variable previuos than the current variable? That is, ${'track_' . $i-1} can I do this?
Why do you want to do that? Likely you should use an array.
@Parth: You can but you should use it like this: ${'track_' . ($i - 1)} to keep the concatenation and the arithmetic clearly separated.
3
<?
for($i = 0; $i < 10; $i++) {
  $name = "track_$i";
  $$name = 'hello';
}

print("==" . $track_3);

Comments

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;

?>


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

?>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.