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>';
}
4
  • can you give an example of output you expect plz Commented Dec 6, 2018 at 19:59
  • Possible duplicate of: stackoverflow.com/questions/2448964/… or stackoverflow.com/questions/1883421/… Commented Dec 6, 2018 at 19:59
  • @Amas the output I expect is only Lucas,593999843424 instead I get Adrian,593998016010 Lucas,593999843424 Commented Dec 6, 2018 at 20:02
  • 1
    Your foreach exits on the first loop Commented Dec 6, 2018 at 20:02

2 Answers 2

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;
}
Sign up to request clarification or add additional context in comments.

Comments

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.