miami
miami

Reputation: 49

Variable variables using in a foreach with php

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.

Upvotes: 0

Views: 53

Answers (5)

Nsagha Kingsly
Nsagha Kingsly

Reputation: 1950

Try This

$aa = [];
$formats = array('100x100', '200x200', '300x300');
foreach ($formats as $val) {
  $aa['html_' . $val] = $val;
}
extract($aa);
echo($html_200x200);

Hope it helps, and also read on PHP Extract

Upvotes: 0

Markus Zeller
Markus Zeller

Reputation: 9090

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"

Upvotes: 0

BuyMyBeard
BuyMyBeard

Reputation: 76

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'];

Upvotes: 0

user3783243
user3783243

Reputation: 5224

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.

Upvotes: 0

Sammitch
Sammitch

Reputation: 32232

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';
}

Upvotes: 1

Related Questions