I need to dynamically compose an array having keys like:
1.1.2
2.1.3
2.1.13
After composing I need to order data by key but I get a result different from needed:
$Vals = array(
"1.1.2" => "First",
"2.1.3" => "Second",
"2.1.13" => "Third"
);
ksort($Vals);
foreach ($Vals as $x => $x_value) {
echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";
}
I get:
Key=1.1.2, Value=First
Key=2.1.13, Value=Third
Key=2.1.3, Value=Second
instead of
Key=1.1.2, Value=First
Key=2.1.3, Value=Second
Key=2.1.13, Value=Third
You're doing simple lexicographical comparison, but what you're trying to compare are version number identifiers, which have their own logic. PHP has a function to compare such standardised version number strings: version_compare
.
uksort($Vals, 'version_compare');