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.
  • Firstrowstart

    Posted at 2012-01-21 21:14:59

    Your knowledge of this subject comes through clearly in this article. I love to read this kind of articles, I hope you will update it. Thank you for sharing it with me.
    honda car insurance

    Reply to comment

  • Bomblawter

    Posted at 2012-01-17 21:36:16

    I am researching this topic for use in a future business I am thinking about starting. Thank you for this information, it has been educational and helpful to me.
    buy backlinks

    Reply to comment

  • Happprze

    Posted at 2012-01-16 23:15:18

    I have been interested in this topic for quite some time. I have been researching it for a couple of hours and found your post to be very interesting. Cheers.
    Presentation Coaching

    Reply to comment

  • Sorrwman

    Posted at 2012-01-15 21:16:21

    I am find information on this topic as I am working on a business project. Thank you posting relative information and its now becoming easier to complete this project.
    Herbal Incense

    Reply to comment

  • TheTimenwes

    Posted at 2012-01-12 18:53:23

    This is a terrific article, and I would like more information if you have any. I am fascinated with this topic and your post has been one of the best I have read.
    Press Release Distribution

    Reply to comment

  • Wentplace

    Posted at 2012-01-11 18:17:01

    Your article has a lot of great information and it has really helped me with my paper for a class I am taking. Do you have any other posts about this topic?
    Lawyer Marketing

    Reply to comment

Post your comments...

Free Downloads