0

So the idea is to remove from one array a list of numbers of other array, but it's only removing the first one, any help to solve this will be appreciated.

$my_array = array("Sandra Loor,593984076233","Adrian,593998016010","Lucas,593999843424");


function myFilter($string) {
    $to_remove = array("593984076233","593998016010");
    foreach($to_remove as $remove)  {
        return strpos($string, $remove) === false;
    }

}

$newArray = array_filter($my_array, 'myFilter');

foreach ($newArray as $val){
    echo $val.'<br>';
}
Ered
  • 465
  • 1
  • 6
  • 23
  • can you give an example of output you expect plz – Amir Hedieh Dec 06 '18 at 19:59
  • Possible duplicate of: https://stackoverflow.com/questions/2448964/php-how-to-remove-specific-element-from-an-array or https://stackoverflow.com/questions/1883421/removing-array-item-by-value – Virginia Dec 06 '18 at 19:59
  • @Amas the output I expect is only `Lucas,593999843424` instead I get `Adrian,593998016010 Lucas,593999843424` – Ered Dec 06 '18 at 20:02
  • 1
    Your `foreach` exits on the **first** loop – choz Dec 06 '18 at 20:02

2 Answers2

2

The problem is that your filter will always return from the first iteration of the loop. This instead will return false if it finds the entry and at the end of the loop will return true (i.e. not found at all)...

function myFilter($string) {
    $to_remove = array("593984076233","593998016010");
    foreach($to_remove as $remove)  {
        if ( strpos($string, $remove) !== false )
            return false;
    }
    return true;
}
Nigel Ren
  • 56,122
  • 11
  • 43
  • 55
2

Another method is to use preg_grep to search the array for the items you want to remove, then use array_diff to remove them.

$my_array = array("Sandra Loor,593984076233","Adrian,593998016010","Lucas,593999843424");
$to_remove = array("593984076233","593998016010");

$to_remove = "/" . implode("|", $to_remove) . "/";
$match = preg_grep($to_remove, $my_array);
$filtered = array_diff($my_array, $match);

var_dump($filtered);
// Lucas,593999843424

https://3v4l.org/PZ4I6


You can also bunch it up to a one liner like this:

$my_array = array("Sandra Loor,593984076233","Adrian,593998016010","Lucas,593999843424");
$to_remove = array("593984076233","593998016010");

$filtered = array_diff($my_array, preg_grep("/" . implode("|", $to_remove) . "/", $my_array));

var_dump($filtered);
Andreas
  • 23,610
  • 6
  • 30
  • 62