Search code examples
phparraysforeachcountarray-key

How to count number keys in array which have the same name


For a flat file blog system, i have some txt files in a direcory data/articles. A txt file looks like this:

id_20200430223049                    // id
Friends                              // category
uploads/mainimage_5eab357970b0d.jpeg // image
Officials wanted                     // title
comment<br />comment<br />comment    // comment

How can i count the number of categories for each category for all the txt files?

So lets say: i have 6 text files. On the 2nd line of each file:

2 of them have category Club

2 of them have category Colleagues

1 has category Family

and 1 has category Friends

What i have so far:

$files = glob("data/articles/*.txt"); // Specify the file directory by extension (.txt)
$cat_lines = array();
foreach($files as $file) {

        $lines = file($file); // all lines of file in array
        $cat_lines[] = strtolower($lines[1]); // grab the category lines and put in array

}

print_r($cat_lines); gives me this output:

Array ( [0] => friends [1] => family [2] => club [3] => colleagues [4] => club [5] => colleagues )

To count the numbers of the keys in the array i use:

echo count (array_keys( $cat_lines, strtolower("Club") ) );

Unfortunatley, it gives me 0 as output instead of 2!!! I dont' understand this...

But besides of this, what i finally want to achieve: How can i create a foreach loop that gives me an output like this:

Friends (1)
Family (1)
Club (2)
Colleagues (2)

Solution

  • Probably your items in $lines have linebreak symbols. This means that club is not the same as club\n.

    Use FILE_IGNORE_NEW_LINES when you use file() or trim value explicitly:

    $lines = file($file, FILE_IGNORE_NEW_LINES); // all lines of file in array WITHOUT linebreaks
    

    As for your second question - array_count_values will give you new array with counts of every element in it:

    $counts = array_count_values($cat_lines);