推送元素到数组中的问题。(array_push)

时间:2019-04-18 23:02:44

标签: php

我做了这个php代码

<?php

if (!isset($_GET['id']) or !is_numeric($_GET['id'])) {
    header('Location: index.php');
} else {
    extract($_GET);
    $id = strip_tags($id);
    require_once 'config/functions.php';

    $errors = array();

    if (!empty($_POST)) {
        extract($_POST);

        $author = strip_tags($author);
        $comment = strip_tags($comment);

        if (empty($author)) {
            $errors = array_push($errors, 'Entre a nickname');
        }

        if (empty($comment)) {
            $errors = array_push($errors, 'Entre a comment');
        }

        var_dump($comment);
        var_dump($author);
        var_dump($errors);
        if (count($errors) == 0) {
            $comment = addComment($id, $author, $comment);
            $sucess = 'Your comment has been sent';
            unset($author);
            unset($comment);
        }
    }
    $article = getArticle($id);
    $comments = getComments($id);
}

但是,当我提交表单时,我看到每次提交都成功,因此我决定转储变量$ errors,$ comment和$ author来尝试解决问题。在这里,无论什么为空,数组$ errors都会出错。我尝试不发表评论或作者,甚至不发表评论,但仍然无法正常工作。
您能帮我解决这个问题吗,因为我真的不知道它来自哪里吗?

1 个答案:

答案 0 :(得分:0)

在PHP array_push()中,该函数允许您将多个元素推入数组,并且该函数的结果是所添加元素的数量。数组本身在第一个参数中作为引用传递。
但是,您不需要调用此函数。

  

注意:如果您使用array_push()向数组中添加一个元素,则最好使用 $array[] = ,因为这样可以无需调用函数。

您可以只使用array append operator

if(!$comment) {
    $errors[] = 'Entre a comment';
}

关于无关的注释,您永远不要信任用户的输入。不要extract()$_GET$_POST超全局变量!

相关问题