Cesar
Cesar

Reputation: 4116

filter an array and get invalid items in php

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!

Upvotes: 0

Views: 87

Answers (1)

nickb
nickb

Reputation: 59709

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

Upvotes: 2

Related Questions