0

I've got a function, which takes in a string parameter for the name of specific page section, this can either be head or body.

The function looks like this:

private $html = [];

public function doStuff($pageSection, array $views)
{
    foreach ($views as $view) {
        //Do some other stuff with view

        $this->html[$pageSection] .= $view->renderOutput();
    }

    print_r($this->html);
}

The renderOutput() function from $view returns a string, and isn't throwing any errors.

When trying to add this string to the $this->html array in a specific array key (the $pageSection), I get the following error:

Notice: Undefined index: body in C:\file.php on line 35

While in the next line (print_r($this->html);, the array is filled with all the strings I wanted to add in the right array key, body.

The function get's called like this:

doStuff('body', array(
           //Array of views
         ));

I tried to remove the concatenate operator and just change the string inside the array key, this threw the same error.

How is this happening? Since I already added the array key in the $this->html[$pageSection] part.

Also, how can I fix this problem?

2
  • I Don't see anything with body here. Maybe it's in renderOutput? Commented May 21, 2016 at 11:33
  • try print_r out pageSection what does it say? Commented May 21, 2016 at 11:34

1 Answer 1

2

String

$this->html[$pageSection] .= 'some data';

means that you concatenate 'some data' to value that should already exist.

In case you don't have key 'body' in $this->html and trying to concatenate to it - you'll see this notice.

You can try something like:

foreach ($views as $view) {
    //Do some other stuff with view

    // init value with empty string.
    if (!isset($this->html[$pageSection])) {
        $this->html[$pageSection] = '';  
    }

    $this->html[$pageSection] .= $view->renderOutput();
}
Sign up to request clarification or add additional context in comments.

5 Comments

may I suggest to move that check outside the foreach loop. No need to check it on each iteration, since the $pageSection is constant.
This did the job! thank you. But why is it possible when you're not in a loop and do something like $array['randKey'] = 123; it works without the error?
Because $array['randKey'] = 123; means create key randKey and assign 123 to it. See - there's no concatenation. Check $array['randKey'] .= 123; and you will get a warning.
It gave the same error when I tried to just assign the string to the array key?
No, it won't. See the difference between assigning = and concatenating .=.

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.