Catch 6 numbers of a string within an array

Asked

Viewed 76 times

0

I have a result of a DOM query in an array, as below:

array(10) {
[0]=>  string(19) "6920709201700750550"
[1]=>  string(16) "6920702500550400"
[2]=>  string(14) "69207000550400"
[3]=>  string(19) "7740641201800750550"
[4]=>  string(16) "7740642500550400"
[5]=>  string(20) "79378270201900750550"
[6]=>  string(16) "7937822500550400"
[7]=>  string(20) "79575693201900750550"
[8]=>  string(16) "7957562500550400"
[9]=>  string(14) "79575600550400"
}

I need to take the first 6 numbers starting from array[0] without repeating on an undefined number. That is, in the example above, I need the numbers 692070, 774064, 793782 and 795756. I’ve tried several answers here from Stackoverflow, but none of them worked. Since I’m not a programmer, it gets a little harder. If you could help, I’d be grateful.

  • 1

    "6 first numbers starting from array[0] without repeating on an indefinite number", could explain this better?

  • You want to do something like SQL GROUP BY?

1 answer

2


You can take the first six digits of this string with a regular expression, ^\d{6}, the result of the capture is stored in $m.

if does two checks, the first is if the capture of preg_match() returned some value and the second is if that value $m[0] exists in the array $novo if there is no it is added.

$arr = ['6920709201700750550', '6920702500550400', '69207000550400', '7740641201800750550', '7740642500550400',
'79378270201900750550', '7937822500550400', '79575693201900750550', '7957562500550400', '79575600550400', '123', '123abc'];

$novo = [];

foreach($arr as $item){
    preg_match('/^\d{6}/', $item, $m);
    if(isset($m[0]) && !in_array($m[0], $novo)){
        $novo[] = $m[0];
    }
}

print_r($novo);

Example - ideone

  • Perfect. Just one question: if I have 50 strings, this code will work the same way?

  • @Johnpablomartins it will not add repeated items idependente quantity.

  • Okay. Just what I needed. It worked perfectly.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.