php - echo variable variable name

563

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

{-code-1}

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

$IMG1 is an variable with a value

125

Answer

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];
}
763

Answer

Solution:

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

640

Answer

Solution:

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.

People are also looking for solutions to the problem: php - PreAuthorize annotation of Symfony2 JMSSecurityExtraBundle not working

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.