Shawnee Posted May 18, 2013 Share Posted May 18, 2013 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! :-) Quote Link to comment Share on other sites More sharing options...
Jessica Posted May 18, 2013 Share Posted May 18, 2013 Read the file into an array, and then use array_count_values Quote Link to comment Share on other sites More sharing options...
jazzman1 Posted May 18, 2013 Share Posted May 18, 2013 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. Quote Link to comment Share on other sites More sharing options...
jazzman1 Posted May 18, 2013 Share Posted May 18, 2013 (edited) 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: appleorange 2xgrapelemon 3xmango Edited May 18, 2013 by jazzman1 Quote Link to comment Share on other sites More sharing options...
Shawnee Posted May 19, 2013 Author Share Posted May 19, 2013 Awesome! Thank you so much!! That works for me perfectly! I really appreciate your help. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.