0

I'm trying to combine a string with variable to get needed variable. This is the code that I think should be fine:

$desc1 = 123;
$desc2 = "asdf";
$desc3 = "asdf123";
for($i = 1; $i<= 3; $i++)
{
    echo 
    "
        <p>$desc".$i."</p>
    ";
}

It should print me:

123

asdf

asdf123

Instead it just prints me:

1

2

3

What's the problem?

3 Answers 3

3

That should work and solve your issue ;)

    $desc[1] = 123;
    $desc[2] = 'asdf';
    $desc[3] = 'asdf123';
    for($i = 1; $i<= 3; $i++)
    {
        echo "<p>$desc[$i]</p>";
    }
?>
Sign up to request clarification or add additional context in comments.

Comments

2

You can do

$desc1 = 123;
$desc2 = "asdf";
$desc3 = "asdf123";

for($i = 1; $i<= 3; $i++) {
    echo "<p>" . ${'desc' . $i } ."</p>";
}

which outputs:

<p>123</p><p>asdf</p><p>asdf123</p>

Variable variables

Comments

-1

What about making them an array of values

$desc = Array( 123, "asdf", "asdf123");

for( $i = 0; $i < sizeof($desc); $i++) 
  echo "<p>${desc[$i]}</p>";

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.