Referencing a PHP variable by using another variable as part of the name

This is kind of a niche scenario, but when you Google making a variable from another variable php, most of the examples involve using a double dollar sign, which may not be what you want to do.

Yes, whenever possible, it makes sense to use arrays instead of weirdly-constructed variable names, but that may depend on the type of data you're working with and how it's stored in the (possibly legacy) database.

$variableaspartofname=1;
${'firstpartofname_'.$variableaspartofname.'_lastpartofname'}='whatevervalueyouwanttoassign';
That's it. If you do that, it will assign whatevervalueyouwanttoassign as the string value to a variable called $firstpartofname_1_lastpartofname.

Join the Conversation

1 Comment

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.