How to check in a TXT if something repeats itself?

3

I have a TXT file storing data separated by | and would like php to check if there is anything there repeating itself as I do?

In TXT the data looks like this:

ID|NOME|TELEFONE|ENDERECO|REFERENCIA 

Every added client saves a line of this. I'd like to check if any phone is repeating itself. Just the phone!

    
asked by anonymous 15.11.2017 / 19:31

1 answer

3

A simple and minimal example:

Text File

ID|NOME|TELEFONE0|ENDERECO|REFERENCIA
ID|NOME|TELEFONE1|ENDERECO|REFERENCIA
ID|NOME|TELEFONE2|ENDERECO|REFERENCIA
ID|NOME|TELEFONE0|ENDERECO|REFERENCIA

PHP code:

<?php

    $item = file("arquivo.txt");

    $items = array_map(function($line)
    {
        return explode("|", $line);
    }, $item);

    $repeat = array();

    foreach($items as $it)
    {       
        $repeat[$it[2]] = 
            isset($repeat[$it[2]])  
            ? (++$repeat[$it[2]])
            : 1;    
    }

    $select = array_filter($repeat, function($item){
        return $item > 1;
    });

    foreach($select as $s) echo $s;

Output:

  

Inotherwords,itcountsrepeatingphonesandshowsyouwhichonesarerepeated,itisaverysimpleway,thatcanevenchange,buttheintentionistoshowsomelogicthatmayfityourfinalcode.>

IDEONE Example

A function can be created to have a simple code of all this, for example:

<?php

    $item = file("arquivo.txt");

    function item_telefone_repetido($item)
    {
        $items = array_map(function($line)
        {
            return explode("|", $line);
        }, $item);

        $repeat = array();

        foreach($items as $it)
        {       
            $repeat[$it[2]] = 
                isset($repeat[$it[2]])  
                ? (++$repeat[$it[2]])
                : 1;    
        }

        $select = array_filter($repeat, function($item){
            return $item > 1;
        });
        return $select;
    }   


    echo '<pre>';   
    print_r(item_telefone_repetido($item));
    echo '<pre>';

Now, just call the function item_telefone_repetido and pass the array of values.

    
15.11.2017 / 20:17