Question

I want to echo a variable variable name, this doesn't work:

echo ($["IMG$i"]);

$i is 1 in this case, and it changes while the for loop goes on.

$IMG1 is an variable with a value

Was it helpful?

Solution

Theoretically, you can do this.

$variablename = 'IMG' . $i;
echo $$variablename;

or simply

echo ${IMG . $i};

This is a PHP language feature called variable variables.

This is a really bad idea. Do not do it.

Instead, build an array.

$images = array('first', 'second', 'third');
foreach($images as $image) {
    echo $image;
}

// or

for ($i = 0; i < count($images); $i++) { // this might be what you already have
    echo $images[$i];
}

OTHER TIPS

Your code contains syntax errors, but assuming you have a variable $arr that is your array, all you need to do is echo $arr["IMG" . $i]

echo $arr['IMG' . $i];

Simple as pie. I don't recommend string interpolation (using variables inside double-quotes) because of it's poor performance and security vulnerabilities.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top