Jump to content

[SOLVED] PHP code in a string variable?


kalevra

Recommended Posts

Is there a way to make something like this work?

 

$count = 3;

$string = "

for ($i=1; $i<$count; $i++){

echo \"This is line number $i\"\n\;

}

";

 

echo $string;

 

I'd like it to echo:

This is line number 1

This is line number 2

This is line number 3

 

But it echoes the "un-processed" php code instead...

 

 

 

Link to comment
https://forums.phpfreaks.com/topic/114608-solved-php-code-in-a-string-variable/
Share on other sites

If you're getting unprocessed PHP output, your webserver may not support PHP at all. The code you gave is full of syntax errors.

 

The following code will work:

<?php
$count = 3;
for ($i=1; $i <= $count; $i++)
     echo "This is line number $i<br>\n";
?>

 

Ken

When there is only one line in an "if" block or any type of loop, you don't need the curly braces.

 

If you want to assign the value to a string and then print it:

<?php
$count = 3;
$string = '';
for ($i=1; $i <= $count; $i++)
     $string .= "This is line number $i<br>\n";
echo $string;
?>

or

<?php
$count = 3;
$tmp = array();
for ($i=1; $i <= $count; $i++)
     tmp[] =  "This is line number $i";
$string = implode("<br>\n",$tmp) . "<br>\n";
echo $string;
?>

 

Ken

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.