Reputation: 47
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?
Upvotes: 0
Views: 54
Reputation: 15213
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>
Upvotes: 2
Reputation: 478
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>";
}
?>
Upvotes: 3
Reputation: 2437
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>";
Upvotes: -1