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

176 Views Asked by At

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

There are 3 best solutions below

0
On BEST ANSWER

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
0
On

Whenever filtering an array by a regex is required, the ideal tool to use is preg_grep().

The pattern will match any (non-newline) character, then match zero or more of any character, then match the first (captured) character.

To retain values which DO NOT contain at least one recurring character, use: (Demo)

var_export(preg_grep('/(.).*\1/', $array, PREG_GREP_INVERT));
// ['8397', '9652', '4378', '8431', '5349', '7068']

To retain values which contain at least one recurring character, use:

var_export(preg_grep('/(.).*\1/', $array));
// ['4149', '3199', '7999']
0
On

This should work for you:

Here I first str_split() each element into a separate array with array_map(). After this I just compare the splitted array with the same array just with array_unique() digits and check if they are the same. If yes I return the implode() number otherwise false. And at the end I just filter the elements with false with array_filter() out.

So in other words I just compare these 2 arrays with they are the same:

array1:

Array
(
    [0] => Array
        (
            [0] => 4
            [1] => 1
            [2] => 4
            [3] => 9
        )

    //...

)

array2:

Array
(
    [0] => Array
        (
            [0] => 4
            [1] => 1
            [3] => 9
        )
    //...

)

Code:

<?php

    $arr = ['4149', '8397', '9652', '4378', '3199', '7999', '8431', '5349', '7068'];
    $arr = array_map("str_split", $arr);

    $result = array_filter(array_map(function($v1, $v2){
        return ($v1 === $v2?implode("", $v1):false);
    }, $arr, array_map("array_unique", $arr)));     

    print_r($result);

?>

output:

Array ( [1] => 8397 [2] => 9652 [3] => 4378 [6] => 8431 [7] => 5349 [8] => 7068 )