Ksort produces the wrong result when working with alphanumeric characters

<?php $a = array( 'a'=>'7833', 'd'=>'1297', 'c'=>'341', '1'=>'67', 'b'=>'225', '3'=>'24', '2'=>'44', '4'=>'22', '0'=>'84' ); ksort($a); print_r($a); 

The above code outputs the following result.

 Array ( [0] => 84 [a] => 7833 [b] => 225 [c] => 341 [d] => 1297 [1] => 67 [2] => 44 [3] => 24 [4] => 22 ) 

Why does ksort give the wrong result?

+4
source share
5 answers

You want to use the flag SORT_STRING. SORT_REGULAR will compare the elements with their current types, in which case the number 1 comes after the string 'a':

 php -r "echo 1 > 'a' ? 'yes' : 'no';" // yes 
+10
source

The default sort is using SORT_REGULAR .

This takes values ​​and compares them as described on the manual page. In the case where the string keys in your example are compared to zero; these strings are converted to numbers (all 0 ) for comparison. If two members are compared as equal, their relative order in the sorted array is undefined. (Quote from the usort () page.)

If you want the sorted output to have numbers before the letters, you should use SORT_NATURAL with PHP 5.4. SORT_STRING also complete the task only if the numbers remain single.

SORT_NATURAL (PHP 5.4 or later) gives keys ordered as:

 0,1,2,4,11,a,b,c 

SORT_STRING provides keys ordered as:

 0,1,11,2,4,a,b,c 

An alternative to SORT_NATURAL for PHP less than 5.4 would use uksort() .

 uksort($a, 'strnatcmp'); 
+7
source

Try ksort($a, SORT_STRING) to force string comparisons on keys.

+1
source

This will work:

 <?php ksort($a,SORT_STRING); ?> 

Checkout another sort_flags here http://www.php.net/manual/es/function.sort.php

Hurrah!

+1
source

See this page for an overview of the various sorting functions in php: http://php.net/manual/en/array.sorting.php

If you want it to be sorted by key, use asort (), which produces this output:

 Array ( [4] => 22 [3] => 24 [2] => 44 [1] => 67 [0] => 84 [b] => 225 [c] => 341 [d] => 1297 [a] => 7833 ) 
-1
source

Source: https://habr.com/ru/post/1403235/


All Articles