0

I keep getting an undefined offset 150 error, but i am not sure what it means or what i should do to debug it. Do to the error line i believe that it has something to do with my for loop.

// Get Datafile
$MyData = file("./tmp/test.txt");
// Get Column Headers

$ColHeads = explode("   ", $MyData[1]);

unset($MyData[1]);
$LastHeader = "";
for ($i = 0;$i <= count($ColHeads);$i++) {
    if ($ColHeads[$i] == $LastHeader) { //<---this is the line that errors
        $ColHeads[$i] = $ColHeads[$i] . "1";
    }
    $LastHeader = $ColHeads[$i];
}

Would anyone have any ideas as to where I am going wrong?

and the error is:

Undefined offset: 150

I am sorry if this is vague. I am not familiar with php and not sure where to start on debugging this... any help would be much appreciated! Thank you!

2 Answers 2

2

Change your for loop:

for ($i = 0;$i < count($ColHeads);$i++) {

The problem is that on the last iteration of the loop, when $i == count($ColHeads), that's going to set $i too high for the number of items in $ColHeads.

You started off right by setting $i = 0. If $ColHeads has 5 items in it, those items have indexes from 0 to 4. Your for loop, as it is, goes up to 5 - and there is no $Colheads[5], so the error is thrown.

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

3 Comments

Thank you!, This was really helpful. I will mark this as the answer as soon as SO lets me.
You're very welcome. I added a little more explanation as to why there was a problem. You were most of the way there - you started the index at zero, you just needed to stop looping before you got to count($ColHeads).
As a side note u should avoid count() in the loop statement rather do it outside as $cnt = count($ColHeads); and use it in loop for ($i = 0;$i < $cnt;$i++). Think if u have a really big array and u are calling count() on each iteration...
2

Array index starts from zero. And ends at Length-1. So it should be:

for ($i = 0;$i < count($ColHeads);$i++) {

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.