2

i have a variables like $srange0 , $srange1, $srange2 $srange3.

i am using to declare some value to each value using for loop.

for($i=0;$i<=3;$i++){
  $srange.$i = $i;
}

but its not working ?

is there any alternative solution for this

1
  • 2
    That a language provides a feature is not a valid motive to use it. Commented Jun 2, 2011 at 4:28

4 Answers 4

6
for($i=0;$i<=3;$i++){
  $var = 'srange'.$i;
  $$var = $i;
}

But, whenever I see variables like that, I'd use an array instead.

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

4 Comments

I shouldn't even say this, but you can do ${'srange'.$i} = $i;.
@konforce but sometimes dynamic variable names are very helpful if you know how to use them properly
@galymzhan, it is never helpful as a replacement for arrays. And in most cases, arrays suffice. Especially here.
@konforce sure, this code isn't perfect and suitable demonstration of dynamic variables
2

Use an array:

$srange = array();
for ($i = 0; $i <= 3; ++$i)
  $srange[$i] = $i;

For the purpose of this particular task, you can also do this:

$srange = range(0, 3);

That also builds the same array as my first code snippet.

Comments

1

The properway to add these dynamic variables will be like this

for($i=0;$i<=3;$i++){
   $name = 'srange'.$i;
   $$name = $i; 
} 

Comments

0

This may be helpful to you:

$srange0;
$srange1;
$srange2;
for($i=0;$i<=3;$i++) {
       $range = "srange".$i;
       $$range = $i;
}
echo $srange2."<br />";
exit;

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.