2

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?

9
  • 2
    Do it like: ${"var".++$counter} = $results['row']; Commented May 28, 2015 at 12:57
  • 2
    Because that's not the correct syntax for variable variables. (Which this would also be a poor use case for. What's wrong with using an array? What's the purpose here?) Commented May 28, 2015 at 12:57
  • 1
    Curly braces can be used for array position, just like square brackets. Darn you PHP! Commented May 28, 2015 at 12:59
  • 1
    @Daan And you answered the last question: stackoverflow.com/a/30504089/3933332 :)?! Commented May 28, 2015 at 13:00
  • 1
    @Rizier123 Oh wow didn't even notice, edited that answer. Commented May 28, 2015 at 13:01

1 Answer 1

4

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'];
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.