What is the most efficient way to write this code?

If I'm inside a ton of PHP code, instead of exiting PHP, I usually write code that contains these variables:

echo "This is how I use a ".$variable." inside a string";

but is it more efficient to exit PHP like this:

?>

Should I instead use the <? echo $variable; ?> like this

<? // then back into PHP

There will be many instances of code throughout the page like this, as I fill the pages with dynamic content or is this too much of a generalization?

+5
source share
6 answers

I suggest only breaking php tags when repeating HTML, not just lines.

This is fine for just a line:

// You don't need to concat, double quotes interpolate variables
echo "This is how I use a $variable inside a string";

But with HTML, personally, I like to do this:

<?php //... ?>
<div>
    <span>This is how I use a <?=$variable?> inside HTML</span>
</div>
<?php //... ?>
+5
source

Using an echo looks a little faster. I made this simple test script:

<?php
$variable = "hello world";
$num = 10000;
$start1 = microtime(true);
for ($i = 0; $i<$num;$i++) {    
    echo "test " . $variable . " test\n";    
}
$time1 = microtime(true) - $start1;
$start2 = microtime(true);
for ($i = 0; $i<$num;$i++) {
    ?>test <?php echo $variable;?> test
<?
}
$time2 = microtime(true) - $start2;
echo "\n$time1\n$time2\n";

The cycle echowas consistently about 25% faster.

, , . - echo , .

+1

echo 'This is how I use a'.$variable.' inside a string';, , .

", .

, , .

, .

0

, <?php ..... ?> -PHP (HTML), . do-while, .

0

- printf() :

// your variable
$my_variable = "Stack Overflow";

printf("Real programmers graduate on %s", $my_variable);

// this prints 'Real programmers graduate on Stack Overflow, 

, . , , ,

0

php. , , concat . :

echo "This is how I use a $variable inside a string";

:

echo "This is how I use a {$variable} inside a string";

( ) . , . .

0

All Articles