0

This is my code to check if the field is empty and it works fine, however i want to check for both, if its empty and if its got less than 10 characters

<pre>
        if(empty($_POST['comments'])){ $errors[]="Please enter a comment."; }
</pre>

I tried this

<pre>
        if(empty($_POST['comments'])){ $errors[]="Please enter a comment."; }
        if(strlen($_POST['comments']) > 10){ $errors[]="Please enter a comment."; }
</pre>

However this then made neither work so i tried which had the same result with neither of them working

<pre>
        if(empty($_POST['comments']) && strlen($_POST['comments']) > 10)){ $errors[]="Your 
         comment must be longer than 10 characters."; }
</pre>

I have tried mb_strlen as well but that changed nothing.

1
  • Your strlen comparison is backwards. You're doing, "if length is greater than 10, then issue an error." Commented Sep 12, 2021 at 21:37

1 Answer 1

1

Your logic is a bit off. You're currently adding the error if the string is empty and longer than 10 characters (which would be a paradox.)

You need to check if the string is empty or less then 10 characters.

Try this:

if (empty($_POST['comments']) || strlen($_POST['comments']) < 10) {
    $errors[] = "Your comment must be longer than 10 characters.";
}

That condition checks if the string is either empty or if the string has less < than 10 characters.

&& means and
|| means or
< means less than
> means greater than

You can read more about logical and comparison operators in the manual.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.