PHP

Buy me a beer or a book?

amazon PayPal - The safer, easier way to donate online!

Looping through variables using concatenation with PHP

Recently a friend was given the task of ordering a group of variables that would be similiar to this:

 

Group of ordered PHP variables
1
2
3
4
$var1 = 10;
$var2 = 20;
$var3 = 30;
$var4 = 40


As you can see these items are not in array, and although it would be a best practice to have the group in array these are unchangeable, possibly an output from an existing system. What does need to be done is place them into an array using concatenation and a simple loop. Below is the loop to do such:

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
//Denotes that the group of vars starts at 1 i.e. $var1
$x=1;
//this specifies the first part of the var name
$varname= 'var';
//using the concatonation on a variable name, and checking if it exists
while (isset(${$varname.$x}) && $tmparr = ${$varname.$x})
{
//the pre-assigned $tmpvar from the loop is then placed into an array
$theArray[$x-1] = $tmpvar;
//increments for the next loop so $var2 is used instead of $var1 repeatedly
$x++;
}
 
//this will then output your populated array.
print_r($theArray);
 

This will output a nice array of items, which you can now use and manipulate a lot easier than the original group of variables.

Free Downloads