Make array search using more than one word

2

I want to search a array and use more than one word, the problem is that I want it to only return something if all words in array exist and not just one, I'm doing the following form but it is not working:

<?php 

if(isset($_POST['palavra'])):

    $palavra = $_POST['palavra'];
    $separa  = explode(' ', $palavra);

    if(in_array(array("você", "bem", "?"), $separa)):
        echo "Bem e você ?";
    endif;

endif;

 ?>
    
asked by anonymous 26.09.2016 / 18:56

2 answers

4

Maybe you can do something like this:

if(isset($_POST['palavra'])):


    $palavra = $_POST['palavra'];
    $separa  = explode(' ', $palavra);

    $palavrasChaves = array("você", "bem", "?");

    $quaisContem = array_intersect($separa, $palavrasChaves);

    sort($palavrasChaves);
    sort($quaisContem);

    if($quaisContem === $palavrasChaves):
        echo "Bem e você ?";
    endif;


endif;

I used array_intersect to check which words of the second array are found in the first. Thus, it returns which are values found in the first array, which are in the second. I apply a sort in both, for the ordering to be similar. Then I compare the two with === . If true, it's because all the words you're looking for are in the list you've separated.

So you can understand a little about array_intersect , I'll give you some examples:

array_intersect(['a', 'b'], ['a']); // ['a']

array_intersect(['a'], ['a', 'b']); // ['a'] ('a' presente no segundo está no primeiro
    
26.09.2016 / 19:08
0

Another alternative is the array_diff function, you can implement it like this < sup> ( credits ) :

function in_array_all($needles, $haystack) {
   return !array_diff($needles, $haystack);
}

The array_diff returns a array with all values of $needles that does not appear in $haystack , to reverse the result is used Logical Denial Helper ! .

Use this:

$palavrasChaves = ["você", "bem", "?"];

if (isset($_POST['palavra']) && $palavra = $_POST['palavra']) {
    $pedacos  = explode(' ', $palavra);

    if (in_array_all($palavrasChaves, $pedacos)) {
        echo "Bem e você ?";
    } else {
        echo "Não estou bem.";
    }
}

See DEMO

    
26.09.2016 / 20:21