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 Build a Simple PHP Application Adding a Contact Form Working with Concatenation and Whitespace

Tibor Ruzinyi
Tibor Ruzinyi
17,968 Points

Why to set a variable to blank ?

Hello, can somebody explain me please why do we need to set the value of $email_body to a blank value to start with it? Thank you :)

<pre><?php
$name = $_POST["name"];
$email = $_POST["email"];
$message = $_POST["message"]
$email_body = "";
$email_body = $email_body . "Name " . $name . "\n";
$email_body = $email_body . "Email " . $email . "\n";
$email_body = $email_body . "Message " . $message ;
echo $email_body;
?></pre>

2 Answers

Kevin Korte
Kevin Korte
28,149 Points

We are initializing the variable, which is considered good practice. This is from the PHP handbook.

It is not necessary to initialize variables in PHP however it is a very good practice. Uninitialized variables have a default value of their type depending on the context in which they are used - booleans default to FALSE, integers and floats default to zero, strings (e.g. used in echo) are set as an empty string and arrays become to an empty array.

http://www.php.net/manual/en/language.variables.basics.php

John Breiner
John Breiner
6,918 Points

You're declaring the variable ahead of time to try and prevent weirdness later on. Kevin does an extremely good job explaining the technicals of it, but basically it's considered good practice to prevent weirdness from cropping up later on.