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 $k
th 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]
.