Jump to content

Don't use echo in functions?


V

Recommended Posts

I took somone's advice on a blog not to use "echo" in functions but "return" instead. So I replaced all echo with return and things weren't working properly anymore. For example code like,

 

while ($row = mysql_fetch_array($result)) { 
		echo "<option value=\"" . $row["cat_id"] . "\">";
		echo $row["category_name"];
		echo "</option>";

 

I use that within a function to have a dropdown list of categories in forms. After using "return" the list was empty. Now I'm not sure, was that guy totally wrong or am I doing something wrong?

 

Link to comment
https://forums.phpfreaks.com/topic/204790-dont-use-echo-in-functions/
Share on other sites

Well what did you replace that with? A suitable replacement would be something like the following:

 

...
$result = '';
while ($row = mysql_fetch_array($result)) { 
$result .= "<option value=\"" . $row["cat_id"] . "\">";
$result .= $row["category_name"];
$result .= "</option>";
}
return $result;
...

echo function_name();

Your original code isn't incorrect, but generally its bad practice to echo data or even produce html within functions unless of course that is the actual intention of the function.

 

For instance, a function called getCatigorys(), should return an array of data, not a html drop down. What if you want to use the same functionality within a script that produces XML?

 

However, you could have another function called arrayToDropDown() that is specifically designed to make a dropdown from an array. Combing these two functions now gives you all the functionality you need to make a dropdown from a simple query while still keeping all the functionality separate enough to be reusable.eg;

 

<?php arrayToDropDown(getCatigorys()); ?>

Btw, the reason what you did wasn't working is because once you return something from a function it doesn't continue processing, that's the end of the function. So you can't return from a single function call multiple times.

 

Edit: Oh, and also to address the indirect question a bit: What the person in the blog post you read was talking about was programming functions without side-effects. I'd suggest reading this article for more information: http://en.wikipedia.org/wiki/Side_effect_(computer_science)

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.