I’m have this array in PHP:
$formats = array('100x100', '200x200', '300x300');
During the foreach, I need to populate the variable $html_100x100
:
foreach($formats as $format) {
$html_100x100 = 'datas';
}
How I can make the variable $html_100x100
dynamic to create one variable per format (based on the formats
array)?
This is what I’ve tried:
foreach($formats as $format) {
${'html_{$format}'} = 'datas';
}
Thanks.
5
Answers
It is considered a bad idea to declare a variable name defined partly by a string. This could potentially create tons of different global variables if you upscale this.
What you want to do here can be accomplished with an associative array (array with string keys instead of indexes).
You can do it like this:
after that, every $format will be a key you can use to access the value in the associative array, like this:
Whenever you think that you need to name variables dynamically like this, what you likely need is an array instead.
This isn’t variable variable but more a dynamic variable name. You can append the variable value to string like this:
The array solution is preferable but this should answer the question. There’s no way to find all
$html_
variables. Where asprint_r
and/orforeach
can be used on an array.With curly braces you can create a variable name "dynamic" during runtime. Your try was almost correct, but did work because of the single quotes, which do not interpolate the string like the double quotes do.
Even this is working, it is much better practice working with arrays instead. Creating variables that way could affect unexpected behaviour.
Output
Try This
Hope it helps, and also read on PHP Extract