Jump to content

putting results of a function into a variable


alecks

Recommended Posts

I want to put the outputs of an include function that is in a basic "fetch while there are still rows" while loop into a variable.

 

ex.

 

while ($result = mysql_fetch_array($query)){
	include("post.inc");	
}

 

and the contents of post.inc are

 

<h1><?php print $result['row_that_was_fetched']; ?></h1>

 

And say that there were three rows, so the product of this while loop would be

 

<h1><?php print $result['row_that_was_fetched']; ?></h1><h1><?php print $result['row_that_was_fetched']; ?></h1><h1><?php print $result['row_that_was_fetched']; ?></h1>

 

I want to put all of those into a variable, so that

 

$variable = <h1><?php print $result['row_that_was_fetched']; ?></h1><h1><?php print $result['row_that_was_fetched']; ?></h1><h1><?php print $result['row_that_was_fetched']; ?></h1>

 

Is it possible to do this?

 

I'm kinda thinking this:

 

while ($result = mysql_fetch_array($query)){
	$variable .= include("post.inc");	
}

 

But I don't think it will work because PHP will interpret it as me wanting to define an anonymous function in $variable. Am I correct or am I just crazy?

 

Any help you can give is very appreciated ^_^

 

-alecks

I'm thinking:

 

//The Call
$loopresults = functionname($query);

 

And the function:

//The Function
function functionname($query)
{

return while ($result = mysql_fetch_array($query))
{
include("post.inc");
}

}

 

But I'm not sure if you can return the results of a loop in this fashion. If it does work, then the results will be stored in the variable $loopresults.

 

 

 

Try this:

 

ob_start();
while ($result = mysql_fetch_array($query)){
    include("post.inc");
}
$string = ob_get_flush();

 

ob_start() will start buffering output, and ob_get_flush() will grab the buffered output and put it in a variable.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.