user737767
user737767

Reputation: 1024

problem with declaring variable in php?

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

Upvotes: 2

Views: 73

Answers (4)

Nirav Jain
Nirav Jain

Reputation: 5107

This may be helpful to you:

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

Upvotes: 0

alex
alex

Reputation: 490153

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

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

Upvotes: 6

Ibu
Ibu

Reputation: 43810

The properway to add these dynamic variables will be like this

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

Upvotes: 1

Matthew
Matthew

Reputation: 48284

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.

Upvotes: 2

Related Questions