Home > Enterprise >  Variable variables using in a foreach with php
Variable variables using in a foreach with php

Time:10-15

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.

CodePudding user response:

Whenever you think that you need to name variables dynamically like this, what you likely need is an array instead.

$formats = array('100x100', '200x200', '300x300');
$html = [];

foreach($formats as $format) {
    $html[$format] = 'datas';
}

CodePudding user response:

This isn't variable variable but more a dynamic variable name. You can append the variable value to string like this:

$formats = array('100x100', '200x200', '300x300');
foreach($formats as $format) {
    ${'html_' . $format} = 'datas';
}

The array solution is preferable but this should answer the question. There's no way to find all $html_ variables. Where as print_r and/or foreach can be used on an array.

CodePudding user response:

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:

$htmlFormats = array();
foreach($formats as $format) {
    $htmlFormats[$format] = 'datas';
}

after that, every $format will be a key you can use to access the value in the associative array, like this:

echo $htmlFormats['100x100'];

CodePudding user response:

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.

$formats = array('100x100', '200x200', '300x300');
foreach ($formats as $format) {
    ${"html_$format"} = $format;
}

var_dump($html_100x100);

Output

string(7) "100x100"
  • Related