array_intersect and match multiple values same time

98 Views Asked by At

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

There are 1 best solutions below

5
Barmar On

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