Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sort numeric string array in php

Tags:

arrays

php

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

like image 522
Prashant Avatar asked Nov 02 '10 08:11

Prashant


People also ask

What is Rsort PHP?

The rsort() function sorts an indexed array in descending order. Tip: Use the sort() function to sort an indexed array in ascending order.

How can I sort an array in PHP without sort method?

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 />"; } ?>

How do I sort a 2d array in PHP?

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.


2 Answers

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 ) 
like image 156
Felix Kling Avatar answered Oct 01 '22 12:10

Felix Kling


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 )  
like image 40
Alex Pliutau Avatar answered Oct 01 '22 11:10

Alex Pliutau