Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I sort an array by string length then by value in PHP?

Currently, I have my array sorting by string length. But, when the string lengths are equal, how do I sort by value?

As an example, my current code:

$array = array("A","BC","AA","C","BB", "B");

function lensort($a,$b){
    return strlen($a)-strlen($b);
}

usort($array,'lensort');

print_r($array);

Outputs:

Array
(
    [0] => C
    [1] => A
    [2] => B
    [3] => BB
    [4] => AA
    [5] => BC
)

But, I'd like it to sort by the following instead:

Array
(
    [0] => A
    [1] => B
    [2] => C
    [3] => AA
    [4] => BB
    [5] => BC
)
like image 361
user2324597 Avatar asked May 01 '13 00:05

user2324597


People also ask

How do you sort an array of strings based on length?

To sort the array by its string length, we can use the Array. sort() method by passing compare function as an argument. If the compare function return value is a. length - b.

How do you sort an array by a specific value in PHP?

PHP - Sort Functions For Arrayssort() - sort arrays in ascending order. rsort() - sort arrays in descending order. asort() - sort associative arrays in ascending order, according to the value. ksort() - sort associative arrays in ascending order, according to the key.

How do I sort a string array in PHP?

$strings = array('/root/mandy/c. pdf', '/root/mandy/a. pdf', '/root/mandy/b. pdf'); sort($strings); print_r($strings);

How can we sort an array without using sort method in PHP?

php function sortArray() { $inputArray = array(8, 2, 7, 4, 5); $outArray = array(); for($x=1; $x<=100; $x++) { if (in_array($x, $inputArray)) { array_push($outArray, $x); } } return $outArray; } $sortArray = sortArray(); foreach ($sortArray as $value) { echo $value . "<br />"; } ?>


1 Answers

Incorporate both checks into your comparator:

function lensort($a,$b){
    $la = strlen( $a); $lb = strlen( $b);
    if( $la == $lb) {
        return strcmp( $a, $b);
    }
    return $la - $lb;
}

You can see from this demo that this prints:

Array
(
    [0] => A
    [1] => B
    [2] => C
    [3] => AA
    [4] => BB
    [5] => BC
)
like image 200
nickb Avatar answered Oct 25 '22 02:10

nickb