Searching in array using more than one word

Asked

Viewed 109 times

2

I want to search one array and use more than one word, the problem is in the fact that I want it to only return something to me if there are all the words in array and not just one, I’m doing it this way but it’s 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;

 ?>

2 answers

4


Maybe you can make it with 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 verify which words of the second array are found in the first. Thus, it returns which values are found in the first array, which are in the second. I apply a sort in both, for the ordering to be similar. I then compare the two with ===. If true, it’s because all the words you searched for are on the list that you’ve broken up.

So you can understand a little bit about array_intersect, I’ll make some examples:

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

array_intersect(['a'], ['a', 'b']); // ['a'] ('a' presente no segundo está no primeiro
  • gave certinho, so the difference between the array_intersect and the in_array is that one searches only one string in an array, and the other searches an array within another ne ?

  • Good use of array_intersect. Why is no comparison made using ==? thus the sort maybe it’s not necessary.

  • @stderr would be needed yet...

0

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

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

The array_diff returns a array with all the values of $needles that nay appear in $haystack, to invert the result is used logical negation operator !.

Use like 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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.