Include vs output functions

I was toying around with printing some formatted sequential data, a module to be precise, within a loop. Something like:

foreach ($data as $row){
      //echo the formatted data for $row;
}

I started wondering, are there any detriments /advantages to using a function over an include? eg.:

foreach ($data as $row){ function output($data); } 
function output($d){ echo "<h1>$d['title']</h1>\n<p>$d['intro']</p><div>$d['story']</div><p>$d['story']</p>"; }

vs

`foreach ($data as $row){ include('module.php'); }` 
where module.php is
 <h1><? echo $d['title'];?></h1>
<p><? echo $d['intro'];?></p>
<div><? echo $d['story'];?> </div>
<p><? echo $d['story'];?></p>";

Pardon the messy pseudo code and as always, thank you in advance for your tips and opinions on this :slight_smile:

I often find including a file much more easier to work with and less messy. When you have to reiterate an output so many times, it just makes it messy for you when you have to redo the output strings. It is also good practice to separate logics, this way, you can manage things in a much easier way.

That’s just how I see it. Not really an advantage.

I too move code out when it starts to make the “primary” code messy. And of course when I want to reuse it elsewhere.

I’m wondering if similar to when a single count()

$array_length = count($array);
for ( $i = 0; $i < $array_length; ...

is more efficient than a looped count()

for ($i = 0; $i < count($array); ...

the function might be in memory and more efficient. Benchmark tests would need to be run to know for certain, but I’m assuming any difference would be negligible especially for more trivial code.

I tend to go for readability and maintenance over efficiency and leave micro-optimization for efficiency sake until a problem becomes noticeable.

2 Likes

The advantage of a function is that it needs to explicitly state its dependencies, whereas an include automatically uses the available variables (so you have a hell of a time figuring out where that variable that the include uses comes from or even what it’s supposed to contain).

3 Likes

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.