David Wheatley
David Wheatley

Reputation: 514

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

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.

Upvotes: 0

Views: 104

Answers (2)

Valentin Sánchez
Valentin Sánchez

Reputation: 131

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.

Upvotes: 1

David Wheatley
David Wheatley

Reputation: 514

I realised the solution was fairly simple:

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

Upvotes: 0

Related Questions