Is there any way to name a variable after another variable, I sort of made up this bit of code which I thought might work but it didn't

<php
$V_Name = 'variable';
$"$V_Name" = 'Hello';
print($variable);
?>

Bit of a long shot I know but I thought it might work,
Any other ideas, I wondered if there was a command like setvariable(); where you could set the variable name as a string but I couldnt find anything.
Regards,
Sam Rudge

Dani AI

Generated

's suggestion (variable variables) is the direct fix that made 's original snippet work: PHP can treat the value of one variable as the name of another. For reference and details about edge cases and syntax, see the PHP manual on variable variables (Variable variables).

For clearer, safer code consider an associative array instead of creating named variables dynamically. Arrays are easier to inspect, iterate, pass around, and avoid polluting the symbol table. Example pattern:

$key = 'variable';
$data = [];
$data[$key] = 'Hello';
echo $data['variable'];

When actual standalone variables are required from keyed data, extract() can create them from an array, but it carries risks (accidental overwrites and injection if keys come from untrusted input). Use it only with controlled data and review the available flags in the docs: extract().

For scope concerns, dynamically creating global variables is done via $GLOBALS, which avoids needing global inside functions but still has maintainability and security caveats. See the globals docs for specifics.

Practical notes: variable names must follow PHP naming rules (letters/underscore followed by letters, numbers, underscores), avoid eval() for dynamic names, and never use unvalidated user input as a variable name. Prefer arrays or objects for collections of values and use extract() or variable variables sparingly and consciously. For general array behavior and idioms, see the manual on arrays (Arrays).

Recommended Answers

All 2 Replies

You can use something called a variable variable(yeah, I know it's weird)

$variable="name";
$$variable = "Shawn";
echo $name; // prints Shawn

Thanks, That worked fine

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.