Search code examples
phparraysduplicatesfilteringpreg-grep

Remove elements from array where the numeric value contains the same digit more than once


I want to remove the numbers from array which have repeated digits in them.

array('4149','8397','9652','4378','3199','7999','8431','5349','7068');

to

array('8397','9652','4378','8431','5349','7068');

I have tried this thing

foreach($array as $key => $value) {
    $data = str_split($value, 1);
    $check = 0;
    foreach($data as $row => $element) {
        $check = substr_count($value, $element);
        if($check != 1) {
            array_diff($array, array($value));
        }
   }
}

Solution

  • You can filter the array using a regular expression that matches:

    • (.) any character
    • .* followed by zero or more characters
    • \1 followed by the first character one more time

    Example code:

    $array = array('4149','8397','9652','4378','3199','7999','8431','5349','7068');
    
    $result = array_filter(
        $array,
        function ($number) {
            return !preg_match('/(.).*\\1/', $number);
        }
    );
    
    echo implode(', ', $result), PHP_EOL;
    

    Output:

    8397, 9652, 4378, 8431, 5349, 7068