0

I have a for-loop ($x++) within another for-loop ($i++) , and I want both $x AND $i to be part of a variable variable:

${'name'.$x.'place'.$i.''} = ...;

Such that I get:

  • $name1place1
  • $name1place2
  • $name1place3
  • $name2place1
  • $name2place2
  • $name3place1 etc. etc.

However, setting variables in the way quoted above does NOT work for me (i.e. with single quotations and two variable variables). I get the error "Notice: Undefined variable [...]".

The following works:

${"name$x"} = ...;

(using double quotations and just one variable variable.)

How can I set variable variables with both $x and $i within the variable name? Thank you!

anmipa
  • 93
  • 1
  • 8

1 Answers1

2

You can do this by using curly braces within your variable name assignment to separate $x from the place:

$x = 4;
$i = 5;
${"name{$x}place{$i}"} = "test";
echo $name4place5;

Output:

test

However it would really make a lot more sense to just use an array:

$name[$x][$i] = "test2";
echo $name[$x][$i];

Demo on 3v4l.org

Nick
  • 138,499
  • 22
  • 57
  • 95