jessica
jessica

Reputation: 1687

Undefined offset error in array index

I have a while loop that runs if the index of an array is null. However, when I use the explode method it throws an undefined offset error for while ($temptext[1] == null). But, if I comment the explode line out, it no longer throws the undefined offset error. I'm confused about that part, because $temptext[1] is null whether it explodes or not. So why is one of them throwing an error, and the other one isn't? And lastly, how do I fix this, so I can use the while loop to compare the empty array index without it throwing an error?

$temptext = null;
$count = 1;
$text = ",";
$textX = "Hello there";

while ($temptext[1] == null && $count > 0) {

$count--;
$temptext = explode($text,$textX,2);

}

P.S: I'm running this snippet on PhpFiddle.org.

Upvotes: 0

Views: 1627

Answers (1)

Blaž Zupančič
Blaž Zupančič

Reputation: 2356

If you check for existance of an array element by using $array[1] == null , php will throw a Notice: Undefined offset: 1 , you should use !isset($array[1]) instead. Otherwise, your code contains no errors.

Upvotes: 1

Related Questions