PHP: Dynamic Variables
Today a came across a situation where I needed to loop through some data and open up a http request using a socket connection, each loop had to open a new connection and the handler had to be stored into a new variable so that each connection could be read separately (opening a new connection using the same variable name would close the previous connection and create a new one).
It’s quite simple if you know exactly how many connections you need to open each time as you can just define the max required variables, but what if one day it needs to open 2 connections then the next it needs 8 but there is no defined maximum either (no one wants to write out 100 variables just encase and it doesn’t meet any of the coding standards either).
A dynamic variable is what we need and PHP has this built in, which has been a life saver as we can declare many unique variables but only as many as we need. Here are some examples; the first creates 10 dynamic variables (dynamic_variable_0, dynamic_variable_1, ……., dynamic_variable_9).
1 2 3 4 5 |
<?php for($a=0; $a < 10; $a++){ ${“dynamic_variable_” . $a} = $a; } ?> |
The following code below outputs the data from the 10 dynamic variables we created in the coding example above.
1 2 3 4 5 |
<?php for($b=0; $b < 10; $b++){ echo ${“dynamic_variable_” . $a}; } ?> |