How can I make a variable's name from another variable AND string?

77 Views Asked by At

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.

2

There are 2 best solutions below

0
David Wheatley On BEST ANSWER

I realised the solution was fairly simple:

$foo = "bar";
$x = $foo . "123"
$$x = "random important variable value"
0
Valentin Sánchez On

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.