Jump to content

newbie count listed occurances


Shawnee

Recommended Posts

Hi, usually I can search and learn and figure PHP out on my own (that's part of the fun of it for me), but this one is a little too big for me to wrap my head around this one. Okay here goes. I have a list of items in a textfile, each item on a separate line:

 

apple

orange

orange

grape

lemon

lemon

lemon

mango

 

All I want to do is run a simple php script that will change that list to look like this:

 

apple

orange 2x

grape

lemon 3x

mango

 

I know some PHP genius will see this and be able to type the answer with one hand tied behind their back, while watching TV at the same time and talking on the phone to someone LOL. So, thank you, in advance, to that person! :-)

Link to comment
https://forums.phpfreaks.com/topic/278128-newbie-count-listed-occurances/
Share on other sites

Try,

<?php
 
$file = array_filter(array_map('trim', file('products.txt')));

$products = (array_count_values($file));

foreach ($products as $key=>$value) {
    echo $key.'('.$value.')'."<br />";
}

Results:

 

apple(1)
orange(2)
grape(1)
lemon(3)
mango(1)

 

 

P.S products.txt is the file that contains strings of products.

Or....if want to be exactly like your output:

 

products.txt

apple

orange

orange

grape

lemon

lemon

lemon

mango
$file = array_filter(array_map('trim', file('products.txt')));

$products = (array_count_values($file));

foreach ($products as $key=>$value) {
 echo ($value == 1) ? $key : $key.' '.$value.'x'; echo '<br />';
}

Results:

 

apple
orange 2x
grape
lemon 3x
mango

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.