0

Say I had the variable $foo which has a value of "bar" and I wanted to make a variable variable from it, but also append the string "123" to it, so that the variable name is $bar123. How would I do this?

I already know that $$foo = "abc123" would make a variable $bar with the value of "abc123", but I don't know how to append a string to this variable name.

David Wheatley
  • 426
  • 6
  • 16
  • 1
    they are called [variable variables](http://php.net/manual/en/language.variables.variable.php), and are almost always a bad idea. very often an array is the better solution –  May 28 '18 at 02:40
  • @smith I already know about variable variables but I don't know how to use them AND append a string to the name. – David Wheatley May 28 '18 at 02:41

2 Answers2

1

Using variable variables, you can do something as the following:

<?php

 $a = "foo";
 $number = 123;
 $b = $a . "$number";

 $$b = "Hello World!";

 echo ${$b};

However, as @smith said, it is better to use associative arrays here.

0

I realised the solution was fairly simple:

$foo = "bar";
$x = $foo . "123"
$$x = "random important variable value"
David Wheatley
  • 426
  • 6
  • 16