0

Basic question using .= (concatenation assignment) in a loop.

This code produces this PHP error:

Notice: Undefined variable: html

for($i=0; $i<4; $i++) {
    $html .= "<h1>Stuff</h1>";
}

If I add an $html = ""; before the loop the error is corrected. Is this the best way to correct this, or am I missing something?

How do I use the .= operator within a loop, and any direction to tutorials to better understand this would be appreciated?

4
  • 2
    You don't miss anything. You corrected the code correctly. Commented Jun 21, 2016 at 19:45
  • 2
    you need to add the $html = "" outside of the loop else you are attempting to concatenate null with a string which wont work. Thus your correction of adding $html = "" before the loop is correct. Commented Jun 21, 2016 at 19:45
  • @Matt Technically, it will work. It generates a notice, but PHP will treat the undefined variable as "" and do the concatenation anyway. Commented Jun 21, 2016 at 19:55
  • Does the answer fixes notice you were receiving? If yes could you accept answer, else please provide more details / questions. Commented Jun 23, 2016 at 0:37

1 Answer 1

1
$html .= "something"; 

Above code is translated to:

$html = $html."something";

so you are trying to concatenate "something" to $html and since $html is not initialised thus you getting the error.

So please initialise the $html above loop and that's the correct way.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.