How to check in a TXT if something repeats?

Asked

Viewed 56 times

3

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

In TXT the data is like this:

ID|NOME|TELEFONE|ENDERECO|REFERENCIA 

Every added customer saves a line from that. I’d like to check if any phones are repeating. Just the phone!

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;

Exit:

inserir a descrição da imagem aqui

In other words, it counts the phones that are repeated and shows you which ones are repeated, it is a very simple way, that can be changed, but, the intention is to show some logic that can be adequate to its final code.

Ideone example

A function can be created to have a simple code of all this, 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>';

I mean, now just call the function item_telefone_repetido and pass the array of values.

Browser other questions tagged

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