Spaceman Spaceman - 2 months ago 6
PHP Question

How to put an INCLUDE into a variable that contains a foreach condition

I have a column within a table that contains multiple ids. I can use each id to define a path to a file, i.e. column contents = "1000 20201" can be defined as variable paths like so...

/1/1000/content-1000.html
/20/20201/content-20201.html


I have written the following code that almost works

$fids = $mcat['mcat_fmemids'];

$fidsarr = explode(' ', $fids);
foreach ($fidsarr as $fid) {
$fincl .= include "../content/".substr($fid, 0, -3)."/".$fid."/content-".$fid.".html";
}

echo "html code that goes above my variable";
echo $fincl;
echo "html code that goes below my variable";


RESULTS FROM ABOVE CODE

The order of code is messed up. The $fincl variable echos above(before) the top half of my html code and a "1" echos for each file where the $fincl variable is specified in the code. see example below.

content-1000.html content
content-20201.html content
"html code that goes above my variable"
"11"
"html code that goes below my variable"


Any ideas what is happening and how to fix it?

Answer

The include instruction does not return the output of the included file. Instead, it returns the value from the return statement within the file, if one exists. Otherwise include will return True if the include was successful.

You are now concatenating the two return values from your include statement (which is True and True). PHP cast this to "11".

$fids = $mcat['mcat_fmemids'];
$fidsarr = explode(' ', $fids);

echo "html code that goes above my variable";
foreach ($fidsarr as $fid) {
   include "../content/".substr($fid, 0, -3)."/".$fid."/content-".$fid.".html";
}
echo "html code that goes below my variable";

If you do not want to include the files at this place, you can fetch the output of the include statement by using the output buffers:

ob_start();
foreach (...) {
   include $some_file;
}
$contents = ob_get_contents();  // get all the content within the buffer
ob_clean();  // clear the buffer
ob_end();   // stop output buffering

print $contents; // print the output