Error/warning PHP 中的消息 "PHP Notice: Undefined offset: 1"

Error/warning message in PHP "PHP Notice: Undefined offset: 1"

我正在使用下面的 PHP 代码,但它正在生成一条 error/warning 消息:

PHP Notice: Undefined offset: 1

代码按预期运行。

while(1) {
    while($data = fgets($irc, 128)) {

        $ex = explode(' ', $data);

        if($ex[0] == "PING"){
            fputs($irc, "PONG ".$ex[1]."\n");
        }

        if($ex[1] == "265"){
            $lusers = str_replace(',', '', $ex[8]);
            $gusers = $ex[10];
        }

    }
}

我看不出代码有什么问题。它按预期运行,那么为什么会生成 error/warning 消息?

使用 print_r($ex) 的建议显示:

Array
(
    [0] => SeIKVfMCuzNTGjZ

)
PHP Notice:  Undefined offset: 1

我应该添加一个 $ex > 0 的检查还是有更好的方法?

我更新了代码,因此它仅在 $ex > 0:

时运行
while(1) {
    while($data = fgets($irc, 128)) {

        $ex = explode(' ', $data);

        if($ex[0] == "PING"){
            fputs($irc, "PONG ".$ex[1]."\n");
        }

        if(count($ex) > 0){

            if($ex[1] == "265"){
                $lusers = str_replace(',', '', $ex[8]);
                $gusers = $ex[10];
            }

        }

    }
}
?>

但我仍然收到 error/warning 消息。怎么可能?

这应该适合你:

if(isset($ex[1]) && $ex[1] == "265") {
    //do stuff

} else {
    echo "Index doesn't exist!";
}