PHP: which is more efficient: concatenated return variable or return each row individually?

I have a sytem where I want to build an HTML table in PHP from data retrieved from a database.

Earlier, I used two different methods for creating HTML and repeating it.

Building the returned variable and echo at the end of the PHP script:

<?php
$data['category']['parts']; // format of the data

$retval = '<table>';
foreach($data as $category) {
  $retval .= '<tr>';
  foreach($category as $data) {
    $retval .= '<td>'.$data.'</td>'
  }
  $retval .= '</tr>';
}
$retval .= '</table>';

echo $retval;

Another method is to echo each line when the code arrives at it:

<?php
$data['category']['parts']; // format of the data

echo '<table>';
foreach($data as $category) {
  echo '<tr>';
  foreach($category as $data) {
    echo '<td>'.$data.'</td>'
  }
  echo '</tr>';
}
echo '</table>';

Which of the two methods is more efficient in terms of CPU / memory usage, as well as for processing speed? Is there a real difference, not just a matter of style?

+4
source share
2 answers

: , . , , , .

, , echo ( , ), retval ( ).

echo:

<?php
$data['category']['parts']; // format of the data

echo '<table>';
foreach($data as $category) {
  echo '<tr>';
  foreach($category as $data) {
    echo '<td>', $data, '</td>';
  }
  echo '</tr>';
}
echo '</table>';

? (, , , , ).

+4

, - .

( included )

<?php
$data['category']['parts']; // format of the data
?>

include ('templates/theFileIWantToShow.php');

---- snip files here. Processing above, template bellow.

<table>
  <?foreach($data as $category):?>
    <tr>
    <?foreach($category as $data):?>
       <td><?=$data?></td>
    <?endforeach;?>
    </tr>
  <?endforeach;?>
</table>

(imho), html- .

:

  • html php
  • ,
  • . / , html- .

, PHP PHP php.ini , 5.4.0.

+3

Source: https://habr.com/ru/post/1606378/


All Articles