skip to Main Content

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


  1. 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'];
    
    Login or Signup to reply.
  2. 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';
    }
    
    Login or Signup to reply.
  3. 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.

    Login or Signup to reply.
  4. 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"
    
    Login or Signup to reply.
  5. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search