Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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,111 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.