php - 基本 PHP 脚本中 undefined offset 注意事项

标签 php post undefined offset notice

这是我在 stackoverflow 上遇到的第一个问题。

这是我的代码:

    <form method="post" action="#">
    <input type="text" name="tags">
    <input type="submit" value="Submit">
</form>
<?php if ($_POST && isset($_POST['tags'])) {
        $tags =  explode(', ', $_POST['tags']);
        for ($i=0; $i <= count($tags); $i++) { 
                echo htmlentities("$i : " . $tags[$i]) . "</br>";
        }
    }
?>

代码可以工作并打印所有由“,”分割的内容,但它给了我一个通知,这让我发疯。

通知

Notice: Undefined offset: 3 in C:\xampp\htdocs..\01.PrintTags.php on line 16 3 :

我希望比我有更多经验的人可以给我一些关于如何解决这个问题的提示,并向我解释为什么会发生这种情况。 提前致谢。

最佳答案

发生这种情况是因为您从 0 开始循环并结束 array 的总长度。从 1 开始循环或从循环中删除 = 符号。按照你的方式,循环将比数组中的值运行多于 1 步。使用这个

<?php if ($_POST && isset($_POST['tags'])) {
        $tags =  explode(', ', $_POST['tags']);
        for ($i=0; $i < count($tags); $i++) { 
                echo htmlentities("$i : " . $tags[$i]) . "</br>";
        }
    }
?>

最好的方法是你可以使用 foreach 。喜欢

foreach($tags as $key=>$val)
{
echo $val;
}

关于php - 基本 PHP 脚本中 undefined offset 注意事项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29715188/

相关文章:

php - MySQL - 查询临时表以从表中检索 2 行

javascript - meteor 未捕获引用错误 : variable is not defined

javascript - 将带有 null 或 undefined 的 javascript 函数绑定(bind)为 thisArg

c++ - 字符串下标超出范围。字符串大小未知,循环字符串直到 null

javascript - 使用 php 创建测验,将数组数据存储在数据库的字段中

javascript - 使用 javascript 自动刷新输入字段

http - 您如何处理可以从 HTTP POST 发送的所有方式?

post - Laravel更新语法-使用数组更新记录

使用 Django 的带有 RESTful API 的 PHP 网站。可能的?好主意?

java - 我的 postman 发帖请求应该是什么样子? (帖子请求的正文)