1

I receive the following PHP notice

PHP Notice:  Undefined offset: 0

Here is a sample of what causes the error.

$file = $_SERVER['DOCUMENT_ROOT']."/savedposts/edited".$post_id.".txt";

$saved_content = file_get_contents($_SERVER['DOCUMENT_ROOT']."/savedposts/".$post_id.".txt");
$cct = 0;
$contexttext = array();
for ($i = 0; $i < strlen($saved_content); $i++) {
    if (substr($saved_content, $i, 9) == "[Context]") {
        $i = $i + 9;
        while (substr($saved_content, $i, 10) !== "[/Context]") {
            $contexttext[$cct] .= substr($saved_content, $i, 1);
            $i++;
        } 
    $cct++;
    }
}

The error is on this line

$contexttext[$cct] .= substr($saved_content, $i, 1);

How to fix the notice.

0

1 Answer 1

2

To replicate this:

$cct = 0;
$contexttext = array();
$contexttext[$cct] .= 'test';

Here 'test' is being appended to $contexttext[$cct], which evaluates to: $contexttext[0]. However there is nothing at [0] yet, because it's an empty array, we can't append to something that doesn't exist

If however you'd done this:

$cct = 0;
$contexttext = array();
$contexttext[$cct] = '';
$contexttext[$cct] .= 'test';

Then the notice would dissapear, because now when we append a string, we have something to append it to

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

1 Comment

Its most likely the right answer but for whatever reason the rest of the function does not run unless i add $contexttext = array('0' => '');

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.