How Do I Create Variable Variables?

In this tutorial, we will learn How To Create Variable Variables as in python it is not possible to do so but in the case of PHP and other programming languages we can do the same as it will be acting the same as a dictionary in python to learn more about the variable of variables follow the post till the end.

As we can see it is nothing similar to the dynamic variables where we create the variables at the time of program execution but here we are creating a variable for storing variables. which we will learn with some example code and try to understand how does it work.

Variable

Variable of Variables

So to make the variables for variables we use a dictionary that we are going to see and understand with an example given below.

# create an empty dictionary
my_ dict = {}

# define a variable name
var_ name = "my_ variable"

# assign a value to the variable name in the dictionary
my_ dict[ var_ name] = 42

# access the value of the variable using the dictionary and the variable name
print( my_ dict [var_ name])  # prints 42

Here first we created a variable my dict which is being a dictionary and on the side of that dictionary, we had stored the variable my name as the key of the dictionary where we can say var name is a variable of a variable and it holds the values that we have given here as 42.

In a similar way, we can store any number of the variables inside my dict variable which is nothing but a variable of variables where as in the case of PHP it is used in a different ways which we can see in an example given below:

// create a variable with a dynamic name
$var_ name = 'my_v ariable';

// create a variable variable and assign a value to it
$$var_ name = 42;

// access the value of the variable variable
echo $my_ variable;  // prints 42

In this piece of code, we have var name as the dynamic name where we have used a double($$) sign which is storing the value 42 where as it is already stored in some other variable to show that it is a variable of variable we use double $.

 

To learn more about How Do I Create Variable Variables in python or in some other programming languages visit: Variable of variables.

To learn more about python programming tutorials, solutions to problems and concepts visit: Python Tutorials And Problems

Leave a Comment

%d bloggers like this: