lockdownd7 Posted September 2, 2009 Share Posted September 2, 2009 I've got an array of file names like: $array[0] = blah.html $array[1] = blah.jpg $array[2] = blah.txt $array[3] = blah2.txt How would I count the number of times a particular file type appears; i.e. in the above example if I counted the number of .txt files, I'd get two. Quote Link to comment https://forums.phpfreaks.com/topic/172768-solved-quick-array-question/ Share on other sites More sharing options...
Prismatic Posted September 2, 2009 Share Posted September 2, 2009 <?php $array = array("blah.html", "blah.jpg", "blah.txt", "blah2.txt"); $file_ext = array_count_file_types($array); print(".txt appears ". $file_ext["txt"] ." times."); function array_count_file_types($arr) { $types = array(); foreach($arr as $item) { $types[substr(strrchr(trim($item), '.'), 1)]++; } return $types; } ?> Output .txt appears 2 times. Quote Link to comment https://forums.phpfreaks.com/topic/172768-solved-quick-array-question/#findComment-910625 Share on other sites More sharing options...
lockdownd7 Posted September 2, 2009 Author Share Posted September 2, 2009 Exactly what I needed! Thank you very much! Quote Link to comment https://forums.phpfreaks.com/topic/172768-solved-quick-array-question/#findComment-910628 Share on other sites More sharing options...
Prismatic Posted September 2, 2009 Share Posted September 2, 2009 One line! <?php $array = array("blah.html", "blah.jpg", "blah.txt", "blah2.txt"); $array = array_count_values(array_map(create_function('$t', 'return substr(strrchr(trim($t), "."), 1);'), $array)); print_r($array); ?> Quote Link to comment https://forums.phpfreaks.com/topic/172768-solved-quick-array-question/#findComment-910692 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.