0

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.

4
  • instead of $temptext[1] == null use isset($temptext[1]) Commented Aug 30, 2015 at 17:28
  • @DannyPhantom If I use that the while loop won't even run. Commented Aug 30, 2015 at 17:30
  • my bad, it's !isset($temptext[1]) Commented Aug 30, 2015 at 17:31
  • @DannyPhantom Yes. You're right. It works now. Can you explain why? The original code works fine on my web server. This only happens on PhpFiddle. And wow. I just got a down vote. Commented Aug 30, 2015 at 17:33

1 Answer 1

1

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.

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

3 Comments

How come that never happens on my web server?
Probably because it has PHP notices turned off.
Again, your code was never throwing an error and was working correctly, it was just noticing, that the array element you were trying to access doesn't exist. PHP doesn't know that you intend to check for existance when using $var == null , that's why !isset($var) is there.

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.