Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Increment number in text file

Tags:

php

I want to record downloads in a text file

Someone comes to my site and downloads something, it will add a new row to the text file if it hasn't already or increment the current one.

I have tried

$filename = 'a.txt';
$lines    = file($filename);
$linea    = array();

foreach ($lines as $line) 
{ 
    $linea[] = explode("|",$line);
}

$linea[0][1] ++;

$a = $linea[0][0] . "|" . $linea[0][1];

file_put_contents($filename, $a);

but it always increments it by more than 1

The text file format is

 name|download_count
like image 805
Brendan Mullan Avatar asked Nov 28 '12 05:11

Brendan Mullan


1 Answers

You're doing your incrementing outside of the for loop, and only accessing the [0]th element so nothing is changing anywhere else.

This should probably look something like:

$filename = 'a.txt';
$lines = file($filename);

// $k = key, $v = value
foreach ($lines as $k=>$v) { 
    $exploded = explode("|", $v);

    // Does this match the site name you're trying to increment?
    if ($exploded[0] == "some_name_up_to_you") {
        $exploded[1]++;

        // To make changes to the source array,
        // it must be referenced using the key.
        // (If you just change $v, the source won't be updated.)
        $lines[$k] = implode("|", $exploded);
    }        
}

// Write.
file_put_contents($filename, $lines);

You should probably be using a database for this, though. Check out PDO and MYSQL and you'll be on your way to awesomeness.


EDIT

To do what you mentioned in your comments, you can set a boolean flag, and trigger it as you walk through the array. This may warrant a break, too, if you're only looking for one thing:

...
$found = false;
foreach ($lines as $k=>$v) { 
    $exploded = explode("|", $v);

    if ($exploded[0] == "some_name_up_to_you") {
        $found = true;
        $exploded[1]++;
        $lines[$k] = implode("|", $exploded);
        break; // ???
    }        
}

if (!$found) {
    $lines[] = "THE_NEW_SITE|1";
}

...
like image 195
Ben Avatar answered Oct 29 '22 18:10

Ben