Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formatting an array value inside a Heredoc

Tags:

I was wondering why I can't do something like {number_format($row['my_number'])} inside a Heredoc. Is there any way around this without having to resort to defining a variable like $myNumber below?

Looked at http://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.nowdoc but found nothing.

CODE

foreach ($dbh -> query($sql) as $row):     $myNumber = number_format($row['my_number']);      $table .= <<<EOT           <tr>           <td>{$row['my_number']}</td> // WORKS           <td>$myNumber</td> // WORKS           <td>{number_format($row['my_number'])}</td> // DOES NOT WORK!           </tr> EOT; endforeach; 
like image 832
Kamil Sindi Avatar asked Nov 26 '11 17:11

Kamil Sindi


People also ask

Should I use heredoc?

Heredoc's are a great alternative to quoted strings because of increased readability and maintainability. You don't have to escape quotes and (good) IDEs or text editors will use the proper syntax highlighting.

What is heredoc syntax?

The heredoc syntax is a way to declare a string variable. The heredoc syntax takes at least three lines of your code and uses the special character <<< at the beginning.

What is heredoc give example?

Heredoc's are equivalent to a double quoted string. That means any variables in the string will get substitued for their respective values. We could rewrite the double quoted string example above as a heredoc:- $foo = 'bar'; echo <<<EOT Hello $foo Goodbye! EOT; // Output:- // Hello bar // Goodbye!

What is a heredoc string?

In computing, a here document (here-document, here-text, heredoc, hereis, here-string or here-script) is a file literal or input stream literal: it is a section of a source code file that is treated as if it were a separate file.


1 Answers

You can execute functions in a HEREDOC string by using {$ variable expressions. You however need to define a variable for the function name beforehand:

$number_format = "number_format";  $table .= <<<EOT       <tr>       <td>{$row['my_number']}</td> // WORKS       <td>$myNumber</td> // WORKS       <td>{$number_format($row['my_number'])}</td> // DOES NOT WORK!       </tr> 

So this kind of defeats the HEREDOCs purpose of terseness.


For readability it might be even more helpful to define a generic/void function name like $expr = "htmlentities"; for this purpose. Then you can utilize almost any complex expression and all global functions in heredoc or doublequotes:

    "   <td>  {$expr(number_format($num + 7) . ':')}  </td>  " 

And I think {$expr( is just more obvious to anyone who comes across such a construct. (Otherwise it's just an odd workaround.)

like image 78
mario Avatar answered Oct 11 '22 05:10

mario