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
)
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.
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.
$strings = array('/root/mandy/c. pdf', '/root/mandy/a. pdf', '/root/mandy/b. pdf'); sort($strings); print_r($strings);
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 />"; } ?>
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
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With