PHP Build a Basic PHP Website Listing and Sorting Inventory Items Creating the Display Function

jlampstack
jlampstack
17,750 Points

Why 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.

Algirdas Lalys
Algirdas Lalys
9,383 Points

Hi 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.

<?php

function add_numbers($num1, $num2) {
  echo $num1 + $num2;
}

// and

function another_add_numbers($num1, $num2) {
  return $num1 + $num2;
}
?>

I'm just trying to understand the question, correct me if I'm wrong:)

3 Answers

Seth Kroger
MOD
Seth Kroger
Treehouse Moderator 56,263 Points

You 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
jlampstack
17,750 Points

Hi 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;
}