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 trial

PHP

Question about function on Mike 4 Shirts project

Hello,

On this function:

function get_list_view_html($product) {

$output = "";

$output = $output . "<li>";
$output = $output . '<a href="' . BASE_URL . 'shirts/' . $product["sku"] . '/">';
$output = $output . '<img src="' . BASE_URL . $product["img"] . '" alt="' . $product["name"] . '">';
$output = $output . "<p>View Details</p>";
$output = $output . "</a>";
$output = $output . "</li>";

return $output;

}

I understand what this function does! its displays our list of products, right! But i have a question:

Why do you need to create an empty $output variable ex.( $output = ""; ) Why is that necessary?

Thank you

1 Answer

Randy Hoyt
STAFF
Randy Hoyt
Treehouse Guest Teacher

Good question! It isn't strictly necessary, but I find it works well to prevent errors in the future for two reasons.

(1) Some earlier code might use a variable name $output, and it might not be blank to start. Explicitly setting it to blank makes sure I won't have any extra text.

(2) Imagine this code:

$name = $first;
$name = $name . " " . $middle;
$name = $name . " " . $last;

Now imagine that you want to add the person's title before the name. It would be easy but wrong to add a line like this:

$name = $title . " ";
$name = $first;
$name = $name . " " . $middle;
$name = $name . " " . $last;

See why that doesn't work? You set the name to the title, but then you set it to the first name and lose the title. You can spend a lot of time trying to figure out why the title isn't showing up. Is your file not saving? Are you working in the wrong environment? I have found it works well to create the variable empty first and then concatenate everything to the end of it:

$name = "";

$name = $name . $first;
$name = $name . " " . $middle;
$name = $name . " " . $last;

Then when I go to add something at the beginning, I don't have to change the line with $first to use concatenation and I'm less likely to make a mistake.

$name = "";

$name = $name . $title . " ";
$name = $name . $first;
$name = $name . " " . $middle;
$name = $name . " " . $last;

Does that help?

Yes, Thanks Randy.