Hasan Setiawan

Write, write, write give your wings on code!

Follow me on GitHub

PHP combine string & variable on composing new variable name

In some case we need to declare new variable name inside iteration, which need to combine index value and string as new name.

You can do this trick to do so:

              
for ($n = 0; $n <= 3; $+=1) {
  ....
}

// we want to get this
$a1 = array('something', 'something else', 'another thing');
$a2 = array('something 2', 'something else 2', 'another thing 2');
$a3 = array('something 3', 'something else 3', 'another thing 3');

//The solution is by wrapping your new variable inside curly brackets,
//allow you to combine string and variable value on creating new variable name.

${'a'.$n} =  array('something', 'something else', 'another thing');

//gives you $a2 if $n is 2
//when you do print_r($a2); will show you this
//array('something', 'something else', 'another thing')
              
            
I hope this post will save your time, cheers!