0

I am receiving this error Undefined offset: -1.

I am pretty sure it is because I am comparing a value of an array index with the value of the previous index, so on the first iteration its failing because there is no -1 index.

for ($i=0; $i<$rows_n; $i++) 
{
    formatTR($i, $rows, 'YEAR');
}


// Function
function formatTR($i, $rows, $year) 
{

    if ($rows[$year][$i] != $rows[$year][$i-1] ) {
        print "<tr class='header-year-tr'><td colspan='2'>{$rows[$year][$i]}</td></tr>";
    }

    print "<tr>";
}

The function checks to see if the previous value of $rows[year][i] is the same as the previous $rows[year][i-1]. If its different, it prints out a formatted < TR >.

Seems like a way to avoid this error would be to first check if the value of $i is zero, but I'm wondering if there is another way. Possibly in my if conditional.

3
  • 5
    You should start with $i = 1. Commented Aug 22, 2012 at 14:08
  • 2
    if ($rows[$year][$i] != $rows[$year][$i-1] ) { should be if (!isset($rows[$year][$i-1]) || $rows[$year][$i] != $rows[$year][$i-1]) { Commented Aug 22, 2012 at 14:10
  • @DaveRandom - Thanks the isset check worked perfectly! Commented Aug 22, 2012 at 14:30

3 Answers 3

1

I think the easest way is to check if $i>0

if ($i > 0 && $rows[$year][$i] != $rows[$year][$i-1] ) {
  // ...
}
Sign up to request clarification or add additional context in comments.

Comments

0

"Undefined offset" is almost always an off-by-one error, and here is the culprit:

if ($rows[$year][$i] != $rows[$year][$i-1] ) {
-------------------------------------^^^^

Make sure you never call this row if $i == 0

Comments

0
function formatTR($i, $rows, $year) 
{
    if($i > 0){
        if ($rows[$year][$i] != $rows[$year][$i-1] ) {
        print "<tr class='header-year-tr'><td colspan='2'>{$rows[$year][$i]}</td></tr>";
        }
    }
    print "<tr>"; //not sure why you have this here.

}

If you want $rows[$year][0] to print a <tr>:

function formatTR($i, $rows, $year) 
{
    if($i > 0){
        if ($rows[$year][$i] != $rows[$year][$i-1] ) {
          print "<tr class='header-year-tr'><td colspan='2'>{$rows[$year][$i]}</td></tr>";
        }
    } else {
        print "<tr class='header-year-tr'><td colspan='2'>{$rows[$year][$i]}</td></tr>";
    }
    print "<tr>"; //not sure why you have this here.

}

1 Comment

Thanks, I ended up using an isset check that DaveRandom Suggested, but this would have also worked well.

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.