Reputation: 41
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.
Upvotes: 1
Views: 15047
Reputation: 9981
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
Upvotes: 2