Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is using curly braces in variables good practice in php [closed]

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

like image 902
Tech4Wilco Avatar asked Sep 14 '11 16:09

Tech4Wilco


3 Answers

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.

like image 107
DaveRandom Avatar answered Nov 12 '22 07:11

DaveRandom


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.

like image 44
hakre Avatar answered Nov 12 '22 05:11

hakre


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>';
like image 39
Alfwed Avatar answered Nov 12 '22 05:11

Alfwed