| re: Array references by name
Janwillem Borleffs wrote:[color=blue]
> Csaba Gabor wrote:[color=green]
> > Is there a way that I can name a "variable" that I want to set, when
> > that "variable" might be an array element?
> >[/color]
>
> You could try the following:
>
> function setMe ($varName, $varVal) {
> $greeting = "Hello";
> $aRay = array("there", "Fred");
> if (is_array($varName)) {
> ${$varName[0]}[$varName[1]] = $varVal;
> } else {
> $$varName = $varVal;
> }
> print( "$greeting " . join(", ", $aRay) . '<br />');
> }
>
> setMe ("greeting", "Goodbye"); // => Goodbye there, Fred
> setMe (array('aRay', 1), "Mom"); // => Hello there, Mom[/color]
Hi and thanks for your reply. I have written something like this,
except that I expect $varName as a string and then parse for
"...[number]". But the problem with that and all other solutions of
this form, including the one that you show, is that all variations must
be thought of in advance.
If, as seems the case, there is no direct method, perhaps the best tack
is to approach it recursively, but that strikes me as a fair amount of
effort for a simple effect.
Csaba Gabor from Vienna |