Array Sort

PHP Programming

PHP Programming Examples

<?php
	$array = array("Java", "C", "PHP", "HTML", "C++", "Python", "JavaScript");
	
	/* Ascending order sort */
	sort($array);
	echo "Ascending order sort<br />";
	
	/* Print dumps information from array */
	var_dump($array);
	
	
	$array1 = array("Java", "C", "PHP", "HTML", "C++", "Python", "JavaScript");
	
	/* Descending order sort */
	rsort($array1);
	echo "<br /><br />Descending order sort<br />";
	
	/* Print human-readable information from array */
	print_r($array1);
	
	
	$array3 = array(1 => "Java", 2 => "C", 3 => "PHP", 4 => "HTML", 5 => "C++", 6 => "Python", 7 => "JavaScript");
	
	/* Ascending order sort as per value */
	asort($array3);
	echo "<br /><br />Ascending order sort as per value<br />";
	
	/* Print human-readable information from array */
	print_r($array3);
	
	
	$array4 = array(1 => "Java", 2 => "C", 3 => "PHP", 4 => "HTML", 5 => "C++", 6 => "Python", 7 => "JavaScript");
	
	/* Descending order sort as per value */
	arsort($array4);
	echo "<br /><br />Descending order sort as per value<br />";
	
	/* Print dumps information from array */
	var_dump($array4);
	
	
	$array5 = array(5 => "Java", 2 => "C", 7 => "PHP", 6 => "HTML", 1 => "C++", 4 => "Python", 3 => "JavaScript");
	
	/* Ascending order sort according to key */
	ksort($array5);
	echo "<br /><br />Ascending order sort according to key<br />";
	
	/* Print human-readable information from array */
	print_r($array5);
	
	
	$array6 = array(5 => "Java", 2 => "C", 7 => "PHP", 6 => "HTML", 1 => "C++", 4 => "Python", 3 => "JavaScript");
	
	/* Descending order sort according to key */
	krsort($array6);
	echo "<br /><br />Descending order sort according to key<br />";
	
	/* Print dumps information from array */
	var_dump($array6);
?>


          /****** Output ******/
          

Ascending order sort


array(7) { [0]=> string(1) "C" [1]=> string(3) "C++" [2]=> string(4) "HTML" [3]=> string(4) "Java" [4]=> string(10) "JavaScript" [5]=> string(3) "PHP" [6]=> string(6) "Python" }




Descending order sort


Array ( [0] => Python [1] => PHP [2] => JavaScript [3] => Java [4] => HTML [5] => C++ [6] => C )




Ascending order sort as per value


Array ( [2] => C [5] => C++ [4] => HTML [1] => Java [7] => JavaScript [3] => PHP [6] => Python )




Descending order sort as per value


array(7) { [6]=> string(6) "Python" [3]=> string(3) "PHP" [7]=> string(10) "JavaScript" [1]=> string(4) "Java" [4]=> string(4) "HTML" [5]=> string(3) "C++" [2]=> string(1) "C" }




Ascending order sort according to key


Array ( [1] => C++ [2] => C [3] => JavaScript [4] => Python [5] => Java [6] => HTML [7] => PHP )




Descending order sort according to key


array(7) { [7]=> string(3) "PHP" [6]=> string(4) "HTML" [5]=> string(4) "Java" [4]=> string(6) "Python" [3]=> string(10) "JavaScript" [2]=> string(1) "C" [1]=> string(3) "C++" }

Learn more about sort, rsort, asort, arsort, ksort and krsort