PHP: Variable variables

Using variable variables (dynamic variable names) in PHP.

695 views
d

By. Jacob

Edited: 2020-05-30 00:49

Variable variables, PHP

Variable variables in PHP are just variables that are dynamically named doing the execution of your script. An alternative name for variable variables could be dynamic variable names.

An interesting feature of dynamic variables, is that we can even use special characters as variable names. In fact, we can even use a doller sign as a variable name, which, perhaps, is a little confusing when done, but nevertheless possible.

In order for this to work, we will have to use Complex (curly) syntax to access the variables that we declare.

Below is probably the easiest example to understand, when it comes to dynamic variable names:

$variable_name = '$'; // Using a single doller sign as a variable name
${$variable_name} = 'Hallo World';
$content = ${'$'}; // Output the content of the special variable

Alternatively, we may also access these variables using the dollar sign ($):

$variable_name = 'my_var'; // Give the variable a name
$$variable_name = 'Hallo World'; // Assign data to the variable
$content = $$variable_name; // Output the content of the variable

Tell us what you think:

  1. In this Tutorial, it is shown how to redirect all HTTP requests to a index.php file using htaccess or Apache configuration files.
  2. How to create a router in PHP to handle different request types, paths, and request parameters.
  3. Tutorial on how to use proxy servers with cURL and PHP
  4. When using file_get_contents to perform HTTP requests, the server response headers is stored in a reserved variable after each successful request; we can iterate over this when we need to access individual response headers.
  5. How to effectively use variables within strings to insert bits of data where needed.

More in: PHP Tutorials