natasha_thomas Posted March 4, 2011 Share Posted March 4, 2011 Folks, I am not able to find any function that will sort an array elements by its element's length. Does such function exist? Quote Link to comment https://forums.phpfreaks.com/topic/229602-sorting-array-decending-by-element-string-length/ Share on other sites More sharing options...
jcbones Posted March 4, 2011 Share Posted March 4, 2011 You thinking of something like: usort() [php <?php function cmp($a, $b) { if (strlen($a) == strlen($b)) { return 0; } return (strlen($a) < strlen($b)) ? 1 : -1; } $a = array('problomatical', 'notaproblic', 'notsomaticalanotam', 'no', 'template'); usort($a, "cmp"); foreach ($a as $key => $value) { echo "$key: $value\n<br />"; } ?> [/code] Quote Link to comment https://forums.phpfreaks.com/topic/229602-sorting-array-decending-by-element-string-length/#findComment-1182935 Share on other sites More sharing options...
natasha_thomas Posted March 4, 2011 Author Share Posted March 4, 2011 I have an array of 50 string elements. I want to short them in descending order of their length. Example Output: AmericaPaintball Brazilpaintball UKpaintball apaintball paintball so on.... Cheers Natasha T Quote Link to comment https://forums.phpfreaks.com/topic/229602-sorting-array-decending-by-element-string-length/#findComment-1182937 Share on other sites More sharing options...
jcbones Posted March 4, 2011 Share Posted March 4, 2011 Which is exactly what I posted. Since I do not have your array names, I couldn't plug those in for you. I would be happy to though! Quote Link to comment https://forums.phpfreaks.com/topic/229602-sorting-array-decending-by-element-string-length/#findComment-1182942 Share on other sites More sharing options...
natasha_thomas Posted March 4, 2011 Author Share Posted March 4, 2011 Which is exactly what I posted. Since I do not have your array names, I couldn't plug those in for you. I would be happy to though! That Array name is: $searchWords It will be so sweet of you to get me started with this. Cheers J Natasha Quote Link to comment https://forums.phpfreaks.com/topic/229602-sorting-array-decending-by-element-string-length/#findComment-1182946 Share on other sites More sharing options...
jcbones Posted March 4, 2011 Share Posted March 4, 2011 Make sure this code block goes below the code that builds your array. function cmp($a, $b) { if (strlen($a) == strlen($b)) { return 0; } return (strlen($a) < strlen($b)) ? 1 : -1; } $a = $searchWords; usort($a, "cmp"); foreach ($a as $key => $value) { echo "$key: $value\n<br />"; } ?> Quote Link to comment https://forums.phpfreaks.com/topic/229602-sorting-array-decending-by-element-string-length/#findComment-1182948 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.