Home » How To Create Dynamic Variable In PHP

How To Create Dynamic Variable In PHP

Last updated on December 30, 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.


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

echo $variableOne;


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.


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

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

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




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.

Additionally, read our guide:

  1. How to Select Data Between Two Dates in MySQL
  2. Error After php artisan config:cache In Laravel
  3. Specified Key Was Too Long Error In Laravel
  4. AJAX PHP Post Request With Example
  5. How To Use The Laravel Soft Delete
  6. How To Add Laravel Next Prev Pagination
  7. cURL error 60: SSL certificate problem: unable to get local issuer certificate
  8. Difference Between Factory And Seeders In Laravel
  9. Laravel: Increase Quantity If Product Already Exists In Cart
  10. How To Calculate Age From Birthdate
  11. How to Convert Base64 to Image in PHP
  12. Check If A String Contains A Specific Word In PHP
  13. Dynamically Populate A Select Field’s Choices In ACF
  14. How To Find Duplicate Records in Database

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