Jump to content

Sorting Array Decending by Element String Length


natasha_thomas

Recommended Posts

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]

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

 

 

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

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 />";
}

?>

Archived

This topic is now archived and is closed to further replies.

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