I have a php array like :
myarr[1] = \"1\",
myarr[2] = \"1.233\",
myarr[3] = \"0\",
myarr[4] = \"2.5\"
the values are actually strings but
Use natsort()
$myarr[1] = "1";
$myarr[2] = "1.233";
$myarr[3] = "0";
$myarr[4] = "2.5";
natsort($myarr);
print_r($myarr);
Output:
Array ( [2] => 0 [0] => 1 [1] => 1.233 [3] => 2.5 )
You can convert your strings to real numbers (floats) and sort them afterwards:
foreach ($yourArray as $key => $value) {
$yourArray[$key] = floatval($value);
}
sort($yourArray, SORT_NUMERIC);
You can use the normal sort function. It takes a second parameter to tell how you want to sort it. Choose SORT_NUMERIC
.
Example:
sort($myarr, SORT_NUMERIC);
print_r($myarr);
prints
Array
(
[0] => 0
[1] => 1
[2] => 1.233
[3] => 2.5
)
Update: For maintaining key-value pairs, use asort (takes the same arguments), example output:
Array
(
[3] => 0
[1] => 1
[2] => 1.233
[4] => 2.5
)
Use the php usort function and in your callback function convert your strings to floats to compare them.