sort the array

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
swetha
Forum Commoner
Posts: 88
Joined: Wed Sep 10, 2008 11:00 pm

sort the array

Post by swetha »

how to sort the contents of an array in ascending and descending order?
User avatar
Kadanis
Forum Contributor
Posts: 180
Joined: Tue Jun 20, 2006 8:55 am
Location: Dorset, UK
Contact:

Re: sort the array

Post by Kadanis »

swetha
Forum Commoner
Posts: 88
Joined: Wed Sep 10, 2008 11:00 pm

Re: sort the array

Post by swetha »

assume the input is either a string or a number.how do i obtain the output for descending as well as ascending order in one command ?i have used the command asort for ascending and arsort for descending,but this works only for strings.For numbers,this doesnt work.can u pls give me one command which works for strings as well as for numbers. ?kindly help.
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: sort the array

Post by requinix »

sort, rsort, asort, and arsort work for numbers too. You'd know that if you bothered looking at the manual page for any of them.
User avatar
s.dot
Tranquility In Moderation
Posts: 5001
Joined: Sun Feb 06, 2005 7:18 pm
Location: Indiana

Re: sort the array

Post by s.dot »

Pay attention to the sorting options, SORT_NUMERIC - in particular.
Set Search Time - A google chrome extension. When you search only results from the past year (or set time period) are displayed. Helps tremendously when using new technologies to avoid outdated results.
swetha
Forum Commoner
Posts: 88
Joined: Wed Sep 10, 2008 11:00 pm

Re: sort the array

Post by swetha »

Code: Select all

 
$str=explode("\n",$str);
sort($str);
 
The thing is we use the function in the above method for sorting numbers as well as strings.
It works for strings coorectly but not for numbers.

FOR eg:
10
11
1
2


This is the output :
1
10
11
2
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: sort the array

Post by requinix »

scottayy wrote:Pay attention to the sorting options, SORT_NUMERIC - in particular.
User avatar
omniuni
Forum Regular
Posts: 738
Joined: Tue Jul 15, 2008 10:50 pm
Location: Carolina, USA

Re: sort the array

Post by omniuni »

You will want to look into using PHP's natural sorting. http://us.php.net/natsort
Post Reply