How to filter values by keyword in the array?

Asked

Viewed 880 times

1

The codes below are not working very well the way I want:

$array = array('January', 'February', 'March', 'April', 'May', 'June');

function filterDataByValue(array $array, $value)
    {
        $filtered = array_filter($array, function ($var) use ($value) {
            return ($var !== $value);
        });

        return $filtered;
    }

   function filterDataByValues(array $array, array $values)
    {
        $filtered = array();
        if (count($values)) {
            foreach ($values as $k => $val) {
               $filtered[$k] = array_values(filterDataByValue($array, $val));

            }
        }
        return $filtered;
    }

    $data = array_values(filterDataByValues($array, array('January','April')));



    print_r($data);

I would like to filter a list of values and remove them from my array. Note, but not by key, by word. Example:

have an array:

$frutas_origem = array('Pêssego', 'Maçã', 'Abacaxi', 'Morango');

Remove the words Apple and Strawberry:

$frutas_remocao = array('Maçã', 'Morango');

I have the result:

$frutas_resultado = array('Pêssego', 'Abacaxi');

The first method I posted removes the value, but what I want is to pass a list and remove the items, example:

$frutas_resultado = metodoRemover($frutas_origem, $frutas_remocao); 

1 answer

0


I managed using array_diff():

function filterDataByValues(array $array, array $values)
{
     $filtered = array_diff($array, $values);
     return $filtered;
}

Browser other questions tagged

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