Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialjlampstack
23,932 PointsWhy is it better to return the HTML function to the code as text assigned to a variable instead of using echo?
My code works, I'd just like a better understanding of the logic behind this.
3 Answers
Seth Kroger
56,414 PointsYou can alter or add to the string before you finally echo it to output. Maybe you want an array of items and filter some out. You can't do that if it is immediately output to the page.
When writing functions there are two things to bear in mind as results. There is the value returned, and there are "side-effects", things the function does to change something or perform some action, but isn't reflected in the return value. echoing to output is a side-effect, and a useful one, but it is usually better to rely on only the return value and not have side effects. It makes the code more modular and easier to reason about and debug.
jlampstack
23,932 PointsHi Algirdas. That's not what I was asking . It's a php function that is called get_item_html($id, $item){}. The full function is below. At the 2:00 minute mark in the video Alena says it's better to assign to a variable called $output, and the return the $output later in our code because it gives us more flexiblility, but I'd like a better understanding of how it gives us more flexibility.
function get_item_html($id, $item) {
$output = "<li><a href=['#']><img src='"
. $item["img"] . "' alt='"
. $item["title"] . "'/>"
. "<p>View Details</p>"
. "</a></li>";
return $output;
}
jlampstack
23,932 PointsThank you Seth Kroger !
Algirdas Lalys
9,389 PointsAlgirdas Lalys
9,389 PointsHi jasonto,
Do you mean PHP functions, because I have never heard about HTML functions. For example you are trying to undestand. What is the difference between echoing value in the function and returning value with a function which you can store in the variable. For example.
I'm just trying to understand the question, correct me if I'm wrong:)