Jump to content

Variable variables in an array


DarkElf

Recommended Posts

PHP has this really useful ability to handle variable variables, these can be written as such:$$variablethis can be really useful in certain circumstances, for instance where you are writing a script to perform the same action on numerous variables but you don't know the name of the variables when writting the script. I've used this in many instances to great effect.I've recently discovered a problem using this in an array though. I'm trying to refer to a specific key in a variable array and it doesn't work. I'm refering to it like so:$$array[$key]This simply doesn't return a value, if i just refer to $$array i get the usual response. Any suggestions?

Link to comment
Share on other sites

http://www.php.net/manual/en/language.variables.variable.php
In order to use variable variables with arrays, you have to resolve an ambiguity problem. That is, if you write $$a[1] then the parser needs to know if you meant to use $a[1] as a variable, or if you wanted $$a as the variable and then the [1] index from that variable. The syntax for resolving this ambiguity is: ${$a[1]} for the first case and ${$a}[1] for the second.
Always read the php.net documentation (including the notes) when in trouble.
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...