Home » How to Create Dynamic Variable in PHP

How to Create Dynamic Variable in PHP

Last updated on May 16, 2020 by

Create dynamic variable in PHP is one of the richest features of PHP. Sometimes it is convenient to create a variable from values or keys. Then we can use that variable as a part of programming.

By using ${} is a way to create dynamic variables in PHP. Let’s create a dynamic variable with the simplest example as below.

<?php

${'variableOne'} = 'Hello World';

echo $variableOne;

/*
Output:

Hello World 

*/

On the above snippet, We have created a dynamic variable $variableOne by wrapping ‘variableOne’ key into ${}. It will output Hello World. Let’s move further with some meaningful example.

<?php

$array = [
	'python' => 'Python',
	'php' => 'PHP',
	'cpp' => 'C++',
];


foreach($array as $key => $value):
	${$key} = $value;
endforeach;

echo $python;
echo '<br/>';
echo $php;
echo '<br/>';
echo $cpp;

/*
Output:

Python
PHP
C++ 

*/

On the above example, We have created a simple associative array. Then we loop that array and created a dynamic variable from its keys and assigned a value. Then we have printed each dynamic variable.

When Dynamic Variable Can be Useful?

Well, this depends on the programming skill and situation, but we can suggest some situations as below.

  1. A dynamic variable can be useful to generate PHP files, for example, You are working on a project in which you need to create multiple sites based on the user’s inputs. So as an initial approach, you need to generate some PHP files like header.php, footer.php, etc., in those files, you need to echo some variables. At that time you can use it.
  2. You can create dynamic variables while reading files like CSV, Excel, Text, etc.

That’s it for now. We hope this article helped you to learn how to create dynamic variables in PHP.

Please let us know in the comments if everything worked as expected, your issues, or any questions. If you think this article saved your time & money, please do comment, share, like & subscribe. Thank you in advance 🙂

 
 

Leave a Comment