-1

In this script, you can see i try validate if 2 values - Jhon 34 -there are in the string called $values the same time, when i send the search i use 2 o 3 words and the idea it´s verification if find exactly this 3 or 2 words, etc, inside array

<?php  
$values="Jhon,Smith,252546,34,house,car,phone";
$post="Jhon 34";

$exp_values=explode(",",$values); 
$exp_post=explode(" ",$post);

$result=array_intersect($exp_post,$exp_values);

foreach ($result as $results) {    
    if(count($result)==count($exp_post)) { 
        echo $results; 
        print "<br>"; 
    }
} 
?>

I use count for show result only if the intersect elements it´s the same number as in the $post, because $post show values i want search inside $values, the result it´s ok if the same words find inside $values

The results it´s wrong because detect one word but i need detect all words i send, if array have all these words result must be ok, if haven´t this result it´s bad

1 Answers1

1

You have the if and foreach backwards. First check if the count is the same to know that the post is valid, then show the results.

And instead of a loop, you can simply implode() $result:

if (count($result) == count($exp_post)) {
    echo implode('<br>', $result);
} else {
    echo "Invalid input";
}
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • I don´t search this , i search the words Jhon 34, in other case if i use Jhon 34 xxx the result it´s bad and don´t exists 3 words exactly but i don´t search br and nothing , thank´s – José Ricardo Cotón Suárez Sep 01 '21 at 21:45
  • That's what this does. If the counts are different, then some of the words in `$post` aren't in `$values`. – Barmar Sep 01 '21 at 21:47
  • Exactly if i search 2 values, the same must be find in the array $values, if the search no have the same values array_intersect don´t must t show nothing or result it´s negative, the problem it´s i think something it´s wrong because don´t works find for search multiple values inside array values – José Ricardo Cotón Suárez Sep 01 '21 at 21:50
  • Is the input `Jhon 34` supposed to be valid or not? – Barmar Sep 01 '21 at 21:54
  • Yes for example if i search Jhon 34 result muss be ok and if for example i search Jhon 34 45 result must be bad, exactly – José Ricardo Cotón Suárez Sep 01 '21 at 22:10