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.

Peter O.
  • 32,158
  • 14
  • 82
  • 96
Vil Ignoble
  • 41
  • 1
  • 2
  • 10

1 Answers1

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

Tom J Nowell
  • 9,588
  • 17
  • 63
  • 91
  • Its most likely the right answer but for whatever reason the rest of the function does not run unless i add $contexttext = array('0' => ''); – Vil Ignoble Aug 20 '14 at 01:18