...

View Full Version : dynamic variable names in a for loop



simonwraight
07-14-2008, 10:03 AM
I have 6 variables
$img1 - $img6 and am trying to loop through them one by one.
From what I found online I thought the code below might work but it does not.

($x=1; $x<7;$x++) {
echo "${'img{$x}'}";
}

Can anyone help please ?

Fou-Lu
07-14-2008, 10:17 AM
for($i = 1; $i <= 6; $i++)
{
echo ${'img' . $i} . "<br />\n";
}

Like that?

You should consider using an array instead, it would be far easier and more optimzed:


$aImages = array();
$aImages[] = '/images/img1.jpg';
$aImages[] = '/images/img2.jpg';
$aImages[] = '/images/img3.jpg';
$aImages[] = '/images/img4.jpg';
$aImages[] = '/images/img5.jpg';
$aImages[] = '/images/img6.jpg';


for ($i = 0; $i < count($aImages); $i++)
{
echo $aImages[$i] . "<br />\n";
}
// Or
foreach ($aImages AS $image)
{
echo $image . "<br />\n";
}

simonwraight
07-14-2008, 10:28 AM
Thankyou, I did consider an array but I chose this way as each image path is stored in a database and there is not always 6 in there so the for loop is to check if there is a file path or not.
Thanks for the help though, I won't pull as much of my hair out now.

Fou-Lu
07-14-2008, 10:37 AM
No problem.
Honestly, if you may not use a magic number (6 in this example) of items, an array is probably a better solution since you can dynamically alter the count for it. I would still recommend the array option (can be pulled from the database in a loop fashion and stored easily) and it will make subsequent checks more usable. The problem is you need to add a check for the existence of the variable if you are choosing to do the magic number route:


for ($i = 1; $i <= 6; $i++)
{
if (isset(${'img' . $i}))
{
echo ${'img' . $i};
}
}

Otherwise you'll get an error trigger indicating that variable img{x} is not a valid variable.

CFMaBiSmAd
07-14-2008, 01:36 PM
It takes three to four times longer to reference a variable-variable than to reference an array variable. I tested this a while ago.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum