Fução to find and remove term in the array does not work with variavél!

Asked

Viewed 65 times

1

implementing in my project the user solution Augusto Vasques in the matter :

How to remove an array from occurrence found within a sub array!

I came across the situation of not being able to search for values stored in variables, only works by inserting strings directly! Follows code.

$arr_val=array('abacaxi','limão');

// array para ser modificado
$frutas = [
  ['maça', 1256],
  ['abacaxi', 1234],
  ['pera', 235],
  ['laranja', 2135],
  ['limão', 2315],
  ['morango', 2351]
];

//laço para testar cada valor do array "$arr_val" e remover

foreach($arr_val as $val_busca){
  $frutas = array_filter($frutas, function ($item){
// aqui o valor de cada fruta a ser encontrado "$val_busca" não funciona por variavél
    return !in_array($val_busca, $item);
  });
}

echo "<pre>";print_r($frutas);echo"</pre>";

I thank you all.

1 answer

2


You need to bring the variable $val_busca within the scope of the function, or else you will not be able to access it:

foreach($arr_val as $val_busca){
  $frutas = array_filter($frutas, function ($item) use ($val_busca) {
    return !in_array($val_busca, $item);
  });
}

This type of treatment is usually required in languages that manage memory with ARC, as is the case with PHP, because if the function does not run synchronously, the memory space of this variable could be released before its callback function can use it.

  • correct, setting $val_search as global within the scope solved the problem!

  • 1

    @Caiolourençon this approach is more efficient than declaring a global because in the example yes a global works, but in the future you want to encapsulate this procedure in a function/method or turn the filter into an asynchronous code the global ceases to work.

  • 1

    Blz, I’ll take recommendations.

Browser other questions tagged

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