Just wondering if there is a way around this (or if it is even possible).
So I have a section of code similar to this. I have a string, with a value that contains square brackets, similar to those used when accessing an array key. I want to create that array key itself by using the strings value. I hope this code makes a little more sense of what I mean.
// String that has a value similar to an array key
$string = 'welcome["hello"]';
$$string = 'thisworks';
// I could then print the array keys value like this
print( $welcome["hello"] );
// This would hopefully output 'thisworks'.
Can’t seem to get it to work correctly, however. Is it possible (or how else can I go about it)?
The following is an example following your variable name syntax that resolves array members as well:
With the following implementation:
As you can not overload variables in PHP, you are limited to the expressiveness of PHP here, meaning there is no write context for variable references as function return values, which requires the additional aliasing:
If something like this does not suit your needs, you need to patch PHP and if not an option, PHP is not offering the language features you’re looking for.
See as well the related question: use strings to access (potentially large) multidimensional arrays.