Martyn
Martyn

Reputation: 73

PHP Counting delimited values in text file that are all on the same line

I need a script to count the number of pipe delmited entries in a text file that are all on one line. I found a script that counts lines and modified it thinking I might get it to work but sadly it still counts the lines, so at present putputs the value 1. Please can you have a look and help me with a solution? The text file looks something like this:

Fred|Keith|Steve|James

The script I was trying is this:

$file1 = "names.txt";
$line = file($file1); 
$count = count(explode("|", $line));
echo "$file1 contains $count words";

Any assistance much appreciated. Many thanks.

Upvotes: 0

Views: 1367

Answers (4)

Arnold Daniels
Arnold Daniels

Reputation: 16573

The fastest way is just to count the pipes and add one. Trim the string to make sure pipes at the beginning and end aren't counted as an item.

<?php
   $contents = file_get_contents('names.txt');
   $count = substr_count(trim($contents, "|\n "), '|') + 1;
   echo "$file1 contains $count words";

Upvotes: 1

Michel Feldheim
Michel Feldheim

Reputation: 18250

You almost did it, there is only a small misunderstanding on how file works:

You have not a single but all lines in you line variable and you can access a single line with a numerical index starting at 0

$nunWords = count( explode ('|', $line[0] ) );

So to count the words on, let's say line 10 you would simply change the index to 9 ( because we start at 0 )

Another example

$lines = file ('yourfile');
foreach ( $lines as $curLine => $line )
{
      echo  "On line " . $curLine+1 . " we got " . count( explode ('|', $line ) ) . " words<br/>\n";
}

Upvotes: 0

Crisp
Crisp

Reputation: 11447

Lots of ways to do this, here's my take...

// get lines as array from file
$lines = file('names.txt');

// get a count for the number of words on each line (PHP > 5.3) 
$counts = array_map(function($line) { return count(explode('|', $line)); }, $lines);
// OR (PHP < 5.3) get a count for the number of words on each line (PHP < 5.3) 
//$counts = array_map(create_function('$line', 'return count(explode("|", $line));'), $lines);

// get the sum of all counts
$count = array_sum($counts);

// putting it all together as a one liner (PHP > 5.3)...
$count = array_sum(array_map(function($line) { return count(explode('|', $line)); }, file('names.txt')));
// or (PHP < 5.3)...
// $count = array_sum(array_map(create_function('$line', 'return count(explode("|", $line));'), file('names.txt')));

Upvotes: 1

Christian Owens
Christian Owens

Reputation: 1116

There are multiple approaches to something like this, different ways to open the file, and different ways to interpret the data.

However, you're going to be looking for something similar to this:

<?php
    $data = file_get_contents("names.txt");
    $count = count(preg_split("/|/", $data));
    echo "The file contains $count words.";
?>

Upvotes: 1

Related Questions