It is necessary to check if the user wrote 2 or more words

Viewed 31

It is necessary to check if the user wrote 2 or more words, if less, then an error should be generated. This must be done using the "explode" method.

my code

<input type="text" name="films" class="form-control mb-3">

<?php   
$films = $_POST['films'];

if(explode(',', $films) < 2) {
    echo 'error';
} else {
    echo $films;
}
2 Answers

Use the count method to count the explode result:

if (count(explode(',', $films)) < 2)
...

@ztom answer's is correct but you can make it even better to handle user separator or mistyping (empty bloc, multiple comma, etc):

if (count(array_filter(array_map('trim', explode(',', $films))) < 2)
...
Related