Search code examples
phparraysvariable-variables

Variable variables doesn't work as expected and is creating an array


I'm using this line of code:

$var{++$counter} = $results['row'];

I've set this up with a goal of creating these variables:

$var1 = row 1
$var2 = row 2
$var3 = row 3

Why is it created an array for $var ? Instead of just defining three variables?


Solution

  • Simply because {} can also be used to access arrays as you can read from the manual:

    Note: Both square brackets and curly braces can be used interchangeably for accessing array elements (e.g. $array[42] and $array{42} will both do the same thing in the example above).

    Means the following 2 lines are the same:

    $var{++$counter}
    $var[++$counter] 
    

    What you want is variable variables, which would be this:

    ${"var" . ++$counter} = $results['row'];