php – Find data from a txt in array and update


I'm making a simple code but I can't get it out to see if you could give me a hand please.

I have a .txt file that presents me with the following data:


Code/idea I use but it's not finished, loops are missing etc:


function multiexplode ($delimiters,$string) {

    $ready = str_replace($delimiters, $delimiters[0], $string);
    $launch = explode($delimiters[0], $ready);
    return  $launch;

    $text = file_get_contents('C:\users.txt');
    $exploded = multiexplode(array("|"," ","\n"),$text);

    $id[i] = trim($exploded[0]);
    $type[i] = $exploded[1];
    $count[i] = $exploded[2];
$datos[] = array('id'=>$id[i],'tipo'=>$type[i],'contador'=>$count[i]);

What I need is that when executing the code the txt is read and it makes/updates an array($datos) so that:

  • Each line of the txt corresponds to a new record in the $datos(id,tipo,contador) array.
  • If the id already exists in the array instead of creating a new record increment the contador key of this id by +1 .

I have tried explode and in-array but the truth is that I cannot verify if the id exists and that it works for me because more than 1000 ids can come in the txt and with explode the thing does not work.

Surely there must be another way to do it.
If you can give me a hand please, I'm stuck and oversaturated looking for info in manuals and I don't know. Greetings


From what I understand, what you want to do is parsear the content in the txt file, save it in an array with format [id, tipo, contador] and if there is already a record with the same id in the array, we must increment the contador .

To do this you can do it like this:


// Matriz asociativa para mapear id y posición
$hash = [];
// Arreglo de resultados
$datos = [];

// Obtenemos un arreglo con las líneas del archivo
$lineas = file('C:\users.txt');
foreach ($lineas as $linea) {

    // Extraemos los datos de la línea
    list($id, $tipo, $contador) = explode('|', trim($linea));

    // Si aún no hemos agregado el id al hash
    if (!isset($hash[$id])) {
        // Guardamos en el hash el id y la posicion en el arreglo de datos
        $hash[$id] = count($datos);

        // Guardamos el id en el arreglo de datos
        $datos[] = [
    } else {
        // Sumamos al contador del id guardado 1



Scroll to Top