0

I want to assign variable name $filename1, $filename2, $filename3 so I write code like this

for ($i=1; $i <= 3; $i++) { 
$filename.$i = 'images/location/'.$i;
}

but It error.

Now I use array to fix problem. But anyway I still wonder, is it possible to assign variable name with ordinal number suffix by using loop?

$filename = array();
for ($i=1; $i <= 3; $i++) { 
$filename[] = 'images/location/'.$i;
}
doflamingo
  • 567
  • 5
  • 23

2 Answers2

2

Yes it is possible.

e.g.

$i = 1;

${'filename' . $i} = 'apple';

echo $filename1; // prints apple
aconnelly
  • 662
  • 1
  • 6
  • 13
0

You CAN pass a variable as a variable name. The way to do so is with $$.

In your case, I would assign the variable name by concatenating the desired string, and then assign the variable in a separate line.

$filename = "filename" . $i;
$$filename = 'images/location/'.$i;
Luke
  • 640
  • 3
  • 10