0

I have a problem with PHP. I'd like to create a new variable each time, my loop runs through. For example: If my loop runs for the first time, it should create a new variable called $loop1, if it runs the second time $loop2 with a different value, third loop - $loop3... Here is a reference of my code, any help is appreciated!

while ($x < count($lines)) {
    $info
    x++;
}
Alex Shesterov
  • 26,085
  • 12
  • 82
  • 103
Tiiill
  • 47
  • 1
  • 3
  • 4
    Why not create an array and add values to that? – Sean Kendle Nov 14 '18 at 20:45
  • I had the same idea, but I'd like to go further on with the variables. – Tiiill Nov 14 '18 at 20:47
  • Use a data structure to store the values and then assign those values to their respective variable. – dustinos3 Nov 14 '18 at 20:48
  • Is there a reason to do this? It is not the normal way to create a set of related values, which is to use an array, vector, list, map (which are all bundled together as "array" in PHP) – Dave S Nov 14 '18 at 20:50
  • 3
    Your next question will be: "How can I use $loopN variables when I don't know how many I got?". So yes, read up on arrays. – mario Nov 14 '18 at 20:54

2 Answers2

5

You can create variables dynamically using braces in PHP, e.g.:

${"loop" . $x} = "some value";

(Reference: PHP "variable variables")

But note that this might be a bad idea in real-world application. It might be more appropriate to use an array or a map instead, e.g.

$loopVars = []; // create a new array
while (...) {
    $loopVars[] = "some value"; // add a new array element
}
Alex Shesterov
  • 26,085
  • 12
  • 82
  • 103
2

I guess you are searching for something like an array.

$data = array();

while ($x < count($lines))
{
    $data[] = ... whatever you want to store
}
Markus Safar
  • 6,324
  • 5
  • 28
  • 44