DrDice DrDice - 9 months ago 57
PHP Question

Php loop and count through txt file

I got a bit of a complex problem. At work we have to count our inventory every month. This is done with a scanner. At each location there can be up to 100 different items. Every item, even the same kind have to be scanned. When each location has been scanned, we print out the list of scanned items. The problem is that each scan has its own line in the txt file (it done not add/subtract multiple counts of the same item)

As the vendor of our system is notoriously slow implementing new functions I thought about a php script that does the following:

  • 1: read every line from the txt file

  • 2: add/substract the count of the same item

  • 3: print out a list with the item number and count.

The txt file is as following:


Where the first 5 digits is the item number. As it is possible to add and substract the next symbol is + or - then the next 5 digits is the count and the N is the "eol"

So somehow I have to put it all in some sort of array and the sort it by item number. And the add/substract and then finally print out the final list

Answer Source

Assuming you've loaded the file into a string, line by line, and is split by a new line, you can do the following; (read code comments)

$strTxtFile = <<<TXT

 * 01234 should have 3 stock
 * 09876 should have 6 stock

$arrProducts = array();
$arrFileLines = explode(PHP_EOL, $strTxtFile);
foreach($arrFileLines as $strFileLine) {
    //Split the lines by the action (+/-)
    $arrStockAction = preg_split("/(\+|\-)/", $strFileLine, NULL, PREG_SPLIT_DELIM_CAPTURE);

    $strProductCode = $arrStockAction[0]; //The first part is the product code
    $strAction = $arrStockAction[1]; //The action (+/-) to the stock
    $intStockAmount = (int) $arrStockAction[2]; //Cast it to an int to get the number

    //Check if the product exists in our array, if not, create it with 0 stock
    if( array_key_exists($strProductCode, $arrProducts) === FALSE ) {
        $arrProducts[$strProductCode] = 0;

    if($strAction === "+") {
        //Add stock
        $arrProducts[$strProductCode] += $intStockAmount;
    } else {
        //Minus stock
        $arrProducts[$strProductCode] -= $intStockAmount;