I want an array of numbers in ascending order according to first digits using PHP. So, for the following input array:
$s = array( 11, 12, 13, 18, 23, 25, 34, 114 );
the resulting ordered array should appear like this:
11 12 13 18 114 23 25 34 .. so on
Your requirement is slightly confusing, if you want to sort naturally, it should be
Array
(
[0] => 11
[7] => 114
[1] => 12
[2] => 13
[3] => 18
[4] => 23
[5] => 25
[6] => 34
)
If this is how you need, just use sort_flags
in sort
function - SORT_STRING
that compares item as string:
$s = array(11,12,13,18,23,25,34,114);
sort($s, SORT_STRING);
print_r($s);
Note: Can you explain how you bring 114 after 18?
From the statement of SO, I think it should compare with twice compare, first for the first digit, then the remains digit.
Compare the first char of the element, then compare the remain part. You can refer to this to compare part of number.
check the live demo
<?php
$s = array(11,12,13,18,23,25,34,114);
usort($s, function($a, $b){
if(substr($a, 0, 1) < substr($b, 0, 1))
return -1;
if(substr($a, 0, 1) > substr($b, 0, 1))
return 1;
return substr($a, 1) - substr($b, 1);
});
print_r($s);
Result,
Array
(
[0] => 11
[1] => 12
[2] => 13
[3] => 18
[4] => 114
[5] => 23
[6] => 25
[7] => 34
)
If the array of numbers were a bit more shuffled and included a larger value as well as duplicates, then the code should presort the array before applying usort(), as follows:
<?php
$s = [ 25, 12, 23, 1006, 13, 114, 11, 34, 18, 13, 112 ];
sort($s);
$func = function($a, $b){
$first_digitA = substr($a, 0, 1);
$first_digitB = substr($b, 0, 1);
if($first_digitA < $first_digitB){
return -1;
}
else
if( $first_digitA > $first_digitB ){
return 1;
}
else
{
return 0;
}
};
usort($s, $func);
print_r($s);
See demo
After presorting by value with sort(), the resulting array looks like this:
[ 11, 12, 13, 13, 18, 23, 25, 34, 112, 114, 1006]
Now, usort() with its callback may be successfully applied, provided that the callback takes advantage of balanced ternary logic, which one may recognize in PHP's strcmp(), such that "-1" denotes that the value of $a is less than that of $b, while "1" means $a is greater than $b. If none of these choices are true, then $a must equal $b in which case the return value is zero. Thus, the comparison restricts itself to examining only the first digit of each numeric pair of values passed to the callback.
Note that the anonymous function definition appears apart from usort(), using instead $func as a paramter since its value holds the user defined function, all for the purpose of improving legibility.