homepage Welcome to WebmasterWorld Guest from 54.146.175.204
register, free tools, login, search, pro membership, help, library, announcements, recent posts, open posts,
Become a Pro Member

Home / Forums Index / Code, Content, and Presentation / PHP Server Side Scripting
Forum Library, Charter, Moderators: coopster & jatar k

PHP Server Side Scripting Forum

    
Ordering PHP Array by Word Count
NoLimits

5+ Year Member



 
Msg#: 3660035 posted 4:33 pm on May 27, 2008 (gmt 0)

I am trying to take the contents of a one dimensional php array and sort them in descending order, by the number of words in each string.

eg... here is my current array

array[0] = the dog was lazy
array[1] = the lazy dog
array[3] = wow that dog sure is lazy

I would like it to re-order as follows:

array[0] = wow that dog sure is lazy
array[1] = the dog was lazy
array[2] = the lazy dog

Any assistance, greatly appreciated.

 

coopster

WebmasterWorld Administrator coopster us a WebmasterWorld Top Contributor of All Time 10+ Year Member



 
Msg#: 3660035 posted 5:55 pm on May 27, 2008 (gmt 0)

A user-defined sort may be your answer:
function cmp($a, $b) 
{
$a = strlen($a);
$b = strlen($b);
if ($a == $b) {
return 0;
}
return ($a > $b) ? -1 : 1;
}
$array[0] = 'the dog was lazy';
$array[1] = 'the lazy dog';
$array[3] = 'wow that dog sure is lazy';
print_r($array);
usort [php.net]($array, 'cmp');
print_r($array);

RonPK

WebmasterWorld Senior Member 10+ Year Member



 
Msg#: 3660035 posted 8:11 pm on May 27, 2008 (gmt 0)

coopster, shouldn't that be
str_word_count() where you used strlen()?
coopster

WebmasterWorld Administrator coopster us a WebmasterWorld Top Contributor of All Time 10+ Year Member



 
Msg#: 3660035 posted 10:08 pm on May 27, 2008 (gmt 0)

by the number of words in each string

I do believe you are correct, RonPK. str_word_count, split, something along those lines. Nice catch!

Global Options:
 top home search open messages active posts  
 

Home / Forums Index / Code, Content, and Presentation / PHP Server Side Scripting
rss feed

All trademarks and copyrights held by respective owners. Member comments are owned by the poster.
Home ¦ Free Tools ¦ Terms of Service ¦ Privacy Policy ¦ Report Problem ¦ About ¦ Library ¦ Newsletter
WebmasterWorld is a Developer Shed Community owned by Jim Boykin.
© Webmaster World 1996-2014 all rights reserved