In php we have predefine function for sorting the array according to the need of the user. Functions are defined below.
sort() - It is used to sort arrays in ascending order
rsort() - It is used to sort arrays in descending order
asort() -It is used to sort associative arrays in ascending order, according to the value
ksort() -It is used to sort associative arrays in ascending order, according to the key
arsort() -It is used to sort associative arrays in descending order, according to the value
krsort() -It is used to sort associative arrays in descending order, according to the key
Example of sort() goes here:
<?php
$phone = array("Iphone", "Samsung", "Nokia");
sort($phone);
?>
Output for the above example is : Iphone Nokia Samsung. It will sort the array in the ascending order.
Example of rsort() goes here:
<?php
$phone = array("Iphone", "Samsung", "Nokia");
rsort($phone);
?>
Output for the above example is : Samsung Nokia Iphone. It will sort the array in the descending order.
Example of asort() goes here:
<?php
$weight = array("shubham"=>"80", "neeraj"=>"76", "mohit"=>"68");
asort($weight);
?>
Output for the above example is :
Key=mohit, value=68
Key=neeraj, value=76
Key=shubham,value=80
It will sort the array in ascending order according to the value.
Example of ksort() goes here:
<?php
$weight = array("shubham"=>"80", "neeraj"=>"76", "mohit"=>"68");
asort($weight);
?>
Output for the above example is :
Key=shubham,value=80
Key=mohit, value=68
Key=neeraj, value=76
It will sort the array in descending order according to the value.
Example of arsort() goes here:
<?php
$weight = array("shubham"=>"80", "neeraj"=>"76", "mohit"=>"68");
asort($weight);
?>
Output for the above example is :
Key=shubham,value=80
Key=mohit, value=68
Key=neeraj, value=76
It will sort the associative array in descending order according to the value.
Example of krsort() goes here:
<?php
$weight = array("shubham"=>"80", "neeraj"=>"76", "mohit"=>"68");
asort($weight);
?>
Output for the above example is :
Key=mohit, value=68
Key=neeraj, value=76
Key=shubham,value=80
It will sort the associative array in ascending order according to the value.
0 Comment(s)