LiveEn
LiveEn

Reputation: 3253

compare and filter values in array in php

i have a csv file containing telephone numbers.

There is about 15 numbers with the area code +44 and 20 numbers beginning with +64 (there are about 40 area codes). i need to echo one number of each set and drop the remains.

i loaded all the content using fgetcsv(). but i cant find a way to do the filtering part. can some please give me an idea how to sort this out in php?

Upvotes: 0

Views: 155

Answers (3)

Shashank Patel
Shashank Patel

Reputation: 459

Try this replace $numbers with your csv file content.

$numbers = array('+1134124', '+11412421', '+41125125','+41125124','+41125144','+41155124','+44125124','+44155124');                          

$final = array();

$received = array();

foreach($numbers as $snKey => $snValue )
{

    $snCode = substr($snValue,0,3);

    if(in_array($snCode,$received))
        continue;
    else
    {
        $received[] = $snCode;
        $final[] = $snValue;
    }
}
print_r($final);

Upvotes: 1

Haim Evgi
Haim Evgi

Reputation: 125466

you can filter them while read line from the file

like:

 $array = array(); 
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
            $prefix = substr($data, 0, 3);
            if(in_array($prefix, $array))
               continue;
            else{
               $array[] = prefix;
               # save the line or echo
            } 

     }

Upvotes: 0

deceze
deceze

Reputation: 522025

$numbers = array('+1134124', '+11412421', '+41125125', …);

$filtered = array_reduce($numbers, function ($f, $num) {
    return $f + array(substr($num, 0, 3) => $num);
}, array());

Upvotes: 1

Related Questions