Question

I want to store some data in an array called $temp, but I got an error that there is an undefined offset. Here's my code:

$temp    = array();
$terms   = $this->DocumentTerms();
$temp[0] = $terms[0][0];

for ($i = 0; $i < sizeof($terms); $i++) {

    $flag = true;

    for ($j = 0; $j < sizeof($terms[$i]); $j++) {

        for ($k = 0; $k < sizeof($temp) || $k < sizeof($terms[$i]); $k++) {

            if ($temp[$k] == $terms[$i][$j]) {

                $flag = false;
                break;
            }
        }

        if ($flag)
            array_push($temp, $terms[$i][$j]);
    }
}

The undefined offset is at this part:

if($temp[$k] == $terms[$i][$j])
Était-ce utile?

La solution

This conditional:

$temp[$k] == $terms[$i][$j]

Should be:

isset($temp[$k]) && $temp[$k] == $terms[$i][$j]

You don't push any data to $temp until the end of the second loop, but you try to access the $kth index of the array in this conditional. If it hasn't been set yet, it will fail. Check to make sure it is set and then continue on with seeing if it equals $terms[$i][$j].

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top