0

I have an array of phone numbers, and I need a fast way to split this array into valid and invalid phone numbers (according to my definition of valid and invalid), something like:

$phone_numbers = array(
    '04165555555',
    '02125555555'
);

$valid_phone_number_regex = '/^0?(416|426|412|424|414)(\d{7})$/i';

I could use array_filter to get all of the valid numbers, but I also need the invalid ones (for reporting issues) in a fast way, the array may hold thousands of numbers!

4
  • ...add array_diff() and you have the invalid ones. Commented Jun 13, 2012 at 22:29
  • If you're performing operations on thousands of rows, you may want to consider doing it in a database as it's optimised for that sort of thing. Failing that, I think your array_filter approach is about the best bet with array_diff for invalids Commented Jun 13, 2012 at 22:31
  • what's wrong with array_filter() to get $valids followed by an array_diff() against the original array and $valids to get the invalid numbers Commented Jun 13, 2012 at 22:31
  • @MarkBaker: there's nothing wrong with that, the only wrong is that didn't occurre to me :-) Commented Jun 13, 2012 at 23:41

1 Answer 1

2

After you get the valid ones from array_filter(), use array_diff() to return all of the elements from the $input_array that are not in the $working array.

$input_array = array( '04165555555', '02125555555');
$working = array_filter( $input_array, function( $el){ return preg_match( '/^0?(416|426|412|424|414)(\d{7})$/i', $el ); });
$not_working = array_diff( $input_array, $working);

Output:

Valid:
array(1) { [0]=> string(11) "04165555555" }
Invalid:
array(1) { [1]=> string(11) "02125555555" } 

Demo

Sign up to request clarification or add additional context in comments.

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.