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.


Posted

in

by

Comments

One response to “Referencing a PHP variable by using another variable as part of the name”

  1. […] Referencing a PHP variable by using another variable as part of the name – Alan Siu […]

Leave a Reply

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