// Generates an E_NOTICE
foreach ($array as $value) {
$html .= $value;
}
// Doesn't generate any error message
$html = '';
foreach ($array as $value) {
$html .= $value;
}
In the first case, the first time though the
foreach, $html is undefined.
So, when you append to it, PHP lets you know you're
appending to an undefined variable. In the second case, the empty
string is assigned to $html above the loop to
avoid the E_NOTICE. The previous two code snippets
generate identical code because the default value of a variable is
the empty string. The E_NOTICE can be helpful
because, for example, you may have misspelled a variable name:
foreach ($array as $value) {
$hmtl .= $value; // oops! that should be $html
}
$html = ''
foreach ($array as $value) {
$hmtl .= $value; // oops! that should be $html
}