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 i want this array to be sorted numerically, also considering float values and maintaining index association.
Please help me out. Thanks
The rsort() function sorts an indexed array in descending order. Tip: Use the sort() function to sort an indexed array in ascending order.
php function sortArray() { $inputArray = array(8, 2, 7, 4, 5); $outArray = array(); for($x=1; $x<=100; $x++) { if (in_array($x, $inputArray)) { array_push($outArray, $x); } } return $outArray; } $sortArray = sortArray(); foreach ($sortArray as $value) { echo $value . "<br />"; } ?>
The array_multisort() function returns a sorted array. You can assign one or more arrays. The function sorts the first array, and the other arrays follow, then, if two or more values are the same, it sorts the next array, and so on.
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 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 )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With