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

Andrew Phythian
Andrew Phythian
18,447 Points

"This works, but it's better with functions like this to return the HTML to the main code as a piece of text instead"

What is the explanation for this line? The HTML that the function was wrapped around was initially echo'd but then replaced by a variable.

2 Answers

Alex Sandro
Alex Sandro
3,361 Points

I have found a good explanation here. Hope this helps!


function function_one() {
  echo "Value1";

function function_two() {
  return "Value2";

$foo = function_one();
$bar = function_two();


S Ananda
S Ananda
9,474 Points

That was a great link. It really helped me to understand it completely. Thanks Alex Sandro.

I imagine it has to do with clarity in the code as well as reusability. With the return value, echo displayText(); will run just fine. but if you don't have a return value, echo displayText() will create an error. Furthermore, if you wanted to test the output of displayText() in a conditiional, it would be much easier to compare if the function returned a value. if (displayText()=="Hello, world!"){echo "You did it!"}