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.

2
  • 1
    they are called variable variables, and are almost always a bad idea. very often an array is the better solution Commented May 28, 2018 at 2:40
  • @smith I already know about variable variables but I don't know how to use them AND append a string to the name. Commented May 28, 2018 at 2:41

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

I realised the solution was fairly simple:

$foo = "bar";
$x = $foo . "123"
$$x = "random important variable value"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.