Some developers uses curly braces in their PHP code and some simply concatenates them.
For example, these 2 lines of code are totally valid in PHP
echo "<h1>{$row['title']}</h1>";
echo "<h1>" . $row['title'] . "</h1>";
The output of the code is the same at the end end but which one is consider a good coding practice?
Thank you, J
Using curly brace syntax is slightly slower. Consider the following test:
<?php
$array = array('key'=>'val');
$start1 = microtime(TRUE);
for ($i = 0; $i < 100000; $i++) {
$str = "<tag>{$array['key']}</tag>";
}
$end1 = microtime(TRUE);
$result1 = $end1 - $start1;
$start2 = microtime(TRUE);
for ($j = 0; $j < 100000; $j++) {
$str = "<tag>".$array['key']."</tag>";
}
$end2 = microtime(TRUE);
$result2 = $end2 - $start2;
$start3 = microtime(TRUE);
for ($k = 0; $k < 100000; $k++) {
$str = '<tag>'.$array['key'].'</tag>';
}
$end3 = microtime(TRUE);
$result3 = $end3 - $start3;
echo "1: $result1\n2: $result2\n3: $result3\n";
?>
On my PHP/5.2.19-win32 system, the first test (with curly braces) is slightly slower (~7%). However, the difference is so small as to be not worth worrying about, and I would say do whatever you are most comfortable with.
Slightly counter-intuitively, the second test is consistently faster than the third (~2%) - double quotes are faster than single quotes - and I would have expected it to be the other way around.
It's useless to ask for best practice, as you have not written which style you prefer. If it helps you to read your strings with curly brackets, use them, they work. There are multiple ways to solve the problem, just to name a few:
echo "<h1>{$row['title']}</h1>";
echo "<h1>" . $row['title'] . "</h1>";
echo "<h1>", $row['title'], "</h1>";
printf("<h1>%s</h1>", $row['title']);
echo sprintf("<h1>%s</h1>", $row['title']);
?><h1><?php echo $row['title']; ?></h1><?php # thx, Jaime :)
...
Choose what is readable for you. Best practices you learn while doing. The language is a tool to suit your needs.
Actually, using single quotes for strings is more efficient in PHP.
So, I would say no, using curly braces around variables in string is not a good practice.
Using the following syntax is both more efficient and more readable (imho) :
echo '<h1>' . $row['title'] . '</h1>';
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With