0

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])
8
  • at which line? what is the error exactly? Commented Apr 17, 2014 at 17:48
  • 1
    As an aside, any particular reason you chose to use sizeof() vs count()? Commented Apr 17, 2014 at 17:49
  • 2
    @summea: sizeof() is an alias of count(). They're exactly the same. Commented Apr 17, 2014 at 17:50
  • @Jason OOO see the update. Commented Apr 17, 2014 at 17:50
  • 1
    @summea: Ah, okay. Maybe they're from a C(++) background, but that's just a guess :-) Commented Apr 17, 2014 at 17:54

1 Answer 1

3

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

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

4 Comments

or array_key_exists($k,$temp)
Yup @JasonOOO, I usually leave that one up to personal preference. I guess array_key_exists() is more obvious as to what you are trying to do, but I like using isset() for consistency across the board. Do you know of any performance differences?
+1: But I wouldn't say func(condition) && $var = $stuff; is the best way to write this. It works, but I'd expand it to a full statement using the ternary operator.
Very true @AmalMurali. I think breaking it up is easiest for explaining what broke and how it is fixed, so I'm going to leave my answer as is.

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.