PHP中foreach()的警告,但仍会循环


Warning for foreach() in PHP but still does loop

我在浏览器调试器中收到警告,但PHP仍然可以工作。为什么我收到警告?提前谢谢。

Warning: Invalid argument supplied for foreach().

HTML:

<form action="" method="post" name="savefile">
    <input id="uniqueID" value="ZF4446A3GZ" name="filename" type="text">
    <input name="textdata[]" type="text">
    <input name="textdata[]" type="text">
    <input name="textdata[]" type="text">
    <input value="Done!" name="submitsave" type="submit">
</form>

PHP:

<?php
if (isset($_POST)){
    foreach($_POST["textdata"] as $text){
        if(!file_exists($_POST['filename'] . ".txt")){
            $file = tmpfile();
        }
        $file = fopen($_POST['filename'] . ".txt","a+");
        while(!feof($file)){
            $old = $old . fgets($file);
        }
        file_put_contents($_POST['filename'] . ".txt", trim($text).PHP_EOL, FILE_APPEND);
        fclose($file);
    }
}
?>

发生此错误是因为您试图对不可迭代的变量进行迭代。

$_POST["textdata"]未设置或不是数组($_POST通常只包含标量和数组)

为了防止出现此错误,您应该检查$_POST["textdata"]是否已设置并且是一个数组。

if ( isset($_POST["textdata"]) && is_array($_POST["textdata"]) ) {
  //DO stuff
}