Вопрос

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])
Это было полезно?

Решение

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].

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top