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:
- $myArray = array(
- 1.432 => 'The',
- 3.42 => 'Brown',
- 3.1111 => 'Fox'
- );
- ksort($myArray);
- var_dump($myArray);
- /*
- Outputs:
- array(2) {
- [1]=>
- string(3) "The"
- [3]=>
- string(3) "Fox"
- }
- */
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:
- $myArray = array(
- '1.432' => 'The',
- '3.42' => 'Brown',
- (string)3.1111 => 'Fox'
- );
- ksort($myArray, SORT_NUMERIC);
- var_dump($myArray);
- /*
- Outputs:
- array(3) {
- ["1.432"]=>
- string(3) "The"
- ["3.1111"]=>
- string(3) "Fox"
- ["3.42"]=>
- string(5) "Brown"
- }
- */
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().
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