0

I did this php code

<?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);
}

However, when I submitted the form I saw that every time the submission was successful so I decided to dump the variables $errors , $comment and $author to try to solve the issue. Here, the array $errors no matter what was empty. I tried not to put the comment or the author or even both but it still isn't working.
Could you help me out with this problem guys because I really don't know from where it comes from?

5
  • You assign the result to the array: $errors = array_push($errors, that is not what you want Commented Apr 18, 2019 at 23:04
  • 1
    Warning Do not use extract() on untrusted data, like user input (e.g. $_GET, $_FILES). Commented Apr 18, 2019 at 23:05
  • 1
    Just do $errors[] = 'Entre a comment'; Commented Apr 18, 2019 at 23:06
  • What do you see for var_dump($comment); and var_dump($author);? Commented Apr 19, 2019 at 0:13
  • var_dump($author); gives me string(8) "nickname" and var_dump($comment); returns string(10) "a comment " Commented Apr 24, 2019 at 19:25

1 Answer 1

0

In PHP array_push() is a function which allows you to push multiple elements into the array, and the result of that function is the number of elements added. The array itself is passed as reference in the first argument.
However, you do not need to call this function.

Note: If you use array_push() to add one element to the array, it's better to use $array[] = because in that way there is no overhead of calling a function.

You can just use the array append operator

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

On unrelated note, you should never trust user input. Do not extract() your $_GET or $_POST super-globals!

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

1 Comment

Thank you for your answer I changed my code as you indicated me however the dumped array is still empty

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.