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

Time:07-27

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" >

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

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

CodePudding user response:

Use the count method to count the explode result:

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

CodePudding user response:

@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)
...
  •  Tags:  
  • php
  • Related