Welcome to WebmasterWorld Guest from

Forum Moderators: coopster & jatar k

Message Too Old, No Replies

Loop array with a variable



2:28 pm on Sep 2, 2010 (gmt 0)

5+ Year Member

I have a PHP code where is have to use a foreach statement multiple times (around 20 times). Is there a way using array and loop it so that i can make this code short.
In the example of the code below you will notice that the only part of the code that changes is the $id1,$id2,$id3......$id20 and $first,$second,$third..........$twentieth
The problem here is that i have to pass a variable to be used in the code below in a array and if i do so, the variable in the array acts like a variable itself.

foreach($id1 as $nexta)
$first = $nexta->get_content();
foreach($id2 as $nexta)
$second= $nexta->get_content();
foreach($id3 as $nexta)
$third = $nexta->get_content();
foreach($id4 as $nexta)
$fourth = $nexta->get_content();

How do i make this code short and work ?

Please guide


3:50 pm on Sep 2, 2010 (gmt 0)

WebmasterWorld Senior Member demaestro is a WebmasterWorld Top Contributor of All Time 10+ Year Member

pemba, my PHP is not great, I am not sure if this will create the variable names from a variable but play around with this. Maybe someone else here can add to it.

counter = 1
vari_array = ['first', 'second', 'third', 'fourth']

foreach (vari_array as var_name){
..for each ($id + counter as $nexta){
....$var_name = $nexta->get_content()
..counter += 1


4:37 pm on Sep 2, 2010 (gmt 0)

WebmasterWorld Senior Member 5+ Year Member

Hi there pemba76,

I have been looking at this for a while trying to think of a good way to do this ;)

I have fixed the value @ 20, alter to suit

//declare an array
$output = array();

//counter and loop
for($i = 0; $i<20; $i++){
foreach($id.$i as $nexta)
$OutPut[$i] = $nexta->get_content();

echo $OutPut[];//enter number 1->20 here

After writing this I cant help but wonder, how many values are held in each $id1, $id2 etc?

You get the idea, but to me this seems a little odd.

If I knew more I would probably engineer something better, but as I have been off caffine for two weeks I can't think in a straight line.

Someone will probably give you a better example than I can, I shall be firing on all cylinders next week ;)



6:56 pm on Sep 2, 2010 (gmt 0)

5+ Year Member

thanks for the respose. after going through the codes above, i simply made a small change to my code and its working now.

Matthew1980 - Its just one value that is held in each $id1, $id2 and this is appened to an array using array_push which is later used as a pointer to display data in different locations of a page.

Featured Threads

Hot Threads This Week

Hot Threads This Month