Jump to content

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

 

Edited by jazzman1
This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.