Monday 16 July 2018

Sorting a PHP Array with a Key of Decimal Type

Sorting a PHP Array with a Key of Decimal Type

There are many PHP functions available that assist with sorting arrays. The one we’ll be talking about in this article is the ksort() function which is intended to sort an array by key.
Now, to sort an array where the keys are of type decimal you would ordinarily think the following would do the job:

  1. $myArray = array(  
  2.     1.432 => 'The',  
  3.     3.42 => 'Brown',  
  4.     3.1111 => 'Fox'  
  5. );  
  6. ksort($myArray);  
  7. var_dump($myArray);  
  8.   
  9. /* 
  10. Outputs:  
  11.  
  12. array(2) { 
  13.   [1]=> 
  14.   string(3) "The" 
  15.   [3]=> 
  16.   string(3) "Fox" 
  17. } 
  18. */  
What you’ll see is that the key has been converted to an integer and, as a result, elements two and three are overwriting each other.
Take a look in the PHP documentation and you’ll see this key bit of information:
The key can either be an integer or a string.“.
As well as:
Floats are also cast to integers, which means that the fractional part will be truncated.“.

THE SOLUTION

Fortunately the solution is a simple one, and one that doesn’t involve you having to change the array much. By sticking with the above example, we’ll modify to work as follows:

  1. $myArray = array(  
  2.     '1.432' => 'The',  
  3.     '3.42' => 'Brown',  
  4.     (string)3.1111 => 'Fox'  
  5. );  
  6. ksort($myArray, SORT_NUMERIC);  
  7. var_dump($myArray);  
  8.   
  9. /* 
  10. Outputs: 
  11.  
  12. array(3) { 
  13.   ["1.432"]=> 
  14.   string(3) "The" 
  15.   ["3.1111"]=> 
  16.   string(3) "Fox" 
  17.   ["3.42"]=> 
  18.   string(5) "Brown" 
  19. } 
  20. */  
Here we’ve done two things:
1. Convert the decimal keys to strings. We’ve done this by wrapping them in quotes, or casting them as strings by prefixing them with ‘(string)‘.
2. Pass ‘SORT_NUMERIC‘ as the second parameter of ksort().
With the above changes done you can see that the output is then in the correct order.

0 comments:

Post a Comment