Home >>PHP Array Functions >PHP arsort() Function

PHP arsort() Function

PHP arsort() Function

PHP arsort() function is used to sort any given input array according to its values. It sorts in a way that the relation between indexes and values is maintained. By default it sort the values in descending order. It accepts two parameters $array and $sort type. It returns a Boolean value True on success and False on failure as result.

Syntax:

arsort($array, $sorttype);

Parameter Values

Parameter Description
array This is a required parameter. This parameter defines the array to sort.
sorttype This is an optional parameter. This parameter defines how to compare the array elements.

Here is an example of arsort() function in PHP:

<html>
<body>
<pre>
<?php
for($i=0;$i<=10;$i++)
{
	$x[]=$i;
}
arsort($x);
print_r($x);
?>
</pre>
</body>
</html>
Output:
Array
(
    [10] => 10
    [9] => 9
    [8] => 8
    [7] => 7
    [6] => 6
    [5] => 5
    [4] => 4
    [3] => 3
    [2] => 2
    [1] => 1
    [0] => 0
)

Example 2:

<html>
<body>
<pre>
<?php
for($i=0;$i<=15;$i++)
{
	$x[]=$i;
}
arsort($x,1);
echo "When sorted as a Numeric Value: <br>";
print_r($x);
arsort($x,2);
echo "When sorted as a String Value: <br>";
print_r($x);
?>
</pre>
</body>
</html>
Output:
When sorted as a Numeric Value: 
Array
(
    [15] => 15
    [14] => 14
    [13] => 13
    [12] => 12
    [11] => 11
    [10] => 10
    [9] => 9
    [8] => 8
    [7] => 7
    [6] => 6
    [5] => 5
    [4] => 4
    [3] => 3
    [2] => 2
    [1] => 1
    [0] => 0
)
When sorted as a String Value: 
Array
(
    [9] => 9
    [8] => 8
    [7] => 7
    [6] => 6
    [5] => 5
    [4] => 4
    [3] => 3
    [2] => 2
    [15] => 15
    [14] => 14
    [13] => 13
    [12] => 12
    [11] => 11
    [10] => 10
    [1] => 1
    [0] => 0
)

No Sidebar ads