List of functions available to sort an PHP array? Explain with example?

Posted by

In PHP, we have six functions for sorting array:

  • sort()= it sort an array in ascending order
  • rsort()= it sort an array in descending order
  • asort()= it sort an array in ascending order, according to the value
  • ksort()= it sort an array in ascending order, according to the key
  • arsort()= it sort an array in descending order, according to the value
  • krsort()= it sort an array in descending order, according to the key

example

<?php
		$num = array(21,23,34,45,1,4,5,);
		 sort($num);

	   $numlength = count($num);
		 for($t = 0; $t < $numlength; $t++) 
		 {
		    echo $num[$t];
		   
		 }
		 
		 
		 echo "<br><br>";
		 echo "<br>";
		 
		 
		 
		 $num = array(21,23,34,45,1,4,5,);
		 rsort($num);

	   $numlength = count($num);
		 for($t = 0; $t < $numlength; $t++) 
		 {
		    echo $num[$t];
			echo "<br>";
		   
		 }
		 
		 echo "<br>";
		 echo "<br>";
		 
		 $team = array("shivam"=>"20", "ravi"=>"22", "abhi"=>"24");
         asort($team);

         foreach($team as $value => $value_v) 
		 {
         echo "Key=" . $value . ", Value=" . $value_v;
         echo "<br>";
         }

          echo "<br>";
		 echo "<br>";
		 
		 $team = array("shivam"=>"20", "ravi"=>"22", "abhi"=>"24");
         ksort($team);

         foreach($team as $value => $value_v) 
		 {
         echo "Key=" . $value . ", Value=" . $value_v;
         echo "<br>";
		 }
		 
		 
		 echo "<br>";
		 echo "<br>";
		 
		 $team = array("shivam"=>"20", "ravi"=>"22", "abhi"=>"24");
         arsort($team);

         foreach($team as $value => $value_v) 
		 {
         echo "Key=" . $value . ", Value=" . $value_v;
         echo "<br>";
		 }

		 
		 
		 
		 echo "<br>";
		 echo "<br>";
		 
		 $team = array("shivam"=>"20", "ravi"=>"22", "abhi"=>"24");
         krsort($team);

         foreach($team as $value => $value_v) 
		 {
         echo "Key=" . $value . ", Value=" . $value_v;
         echo "<br>";
		 }


?>

output

14521233445


45
34
23
21
5
4
1


Key=shivam, Value=20
Key=ravi, Value=22
Key=abhi, Value=24


Key=abhi, Value=24
Key=ravi, Value=22
Key=shivam, Value=20


Key=abhi, Value=24
Key=ravi, Value=22
Key=shivam, Value=20


Key=shivam, Value=20
Key=ravi, Value=22
Key=abhi, Value=24
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x