PHP Tutorial Tutorials - PHP Sorting Arrays

PHP Sorting Arrays

PHP provides a number of predefined functions to sort an array.

  • sort() , rsort() : For sorting an indexed arrays by values
  • asort() , arsort() : For sorting an associative arrays by value
  • ksort() , krsort() : For sorting an associative arrays by key

Sort an Indexed Arrays in Ascending Order

The sort() function is used for sorting the elements of the indexed array in ascending order by values. Elements will be arranged from lowest to highest.

<?php
$colors = array("red", "orange", "blue", "green");
sort($colors);
var_dump($colors); // array("blue", "green", "orange", "red");

$colors = array(1=>"red", 3=>"orange", 4=>"blue", 2=>"green");
sort($colors);
var_dump($colors); // array(0=>"blue", 1=>"green", 2=>"orange", 3=>"red");

$colors = array("red", "#333", "blue", "green");
sort($colors);
var_dump($colors); // array("#333", "blue", "green", "red");
?>

Sort an Indexed Arrays in Reverse Order(Descending Order)

The rsort() function is used to sort an array in reverse order by values.

<?php
$colors = array("red", "orange", "blue", "green");
rsort($colors);
var_dump($colors); // array("red", "orange", "green", "blue");
?>

Sort an Associative Arrays in Ascending Order By Value

The asort() function is used to sort an associative array in ascending order according to it's value.
The main difference from sort() function is that asort() would maintain index association.

<?php

$colors = array(1=>"red", 3=>"orange", 4=>"blue", 2=>"green");
sort($colors);
var_dump($colors); 
// array(0=>"blue", 1=>"green", 2=>"orange", 3=>"red");

$colors = array(1=>"red", 3=>"orange", 4=>"blue", 2=>"green");
asort($colors);
var_dump($colors);
// array(4=>"blue", 2=>"green", 3=>"orange", 1=>"red");
?>

Sort an Associative Arrays in Reverse Order By Value

The function arsort() is like asort() but sort the array in reverse order.

<?php
$colors = array(1=>"red", 3=>"orange", 4=>"blue", 2=>"green");
arsort($colors);
var_dump($colors);
// array(1=>"red", 3=>"orange", 2=>"green", 4=>"blue");
?>

Sort an Associative Arrays in Ascending Order By Key

The ksort() function is similar to asort() but it sort the array according to it's key.

<?php
$colors = array(1=>"red", 5=>"orange", 4=>"blue", 2=>"green");
ksort($colors);
var_dump($colors);
// array(1=>"red", 2=>"green", 4=>"blue", 5=>"orange");
?>

Sort an Associative Arrays in Reverse Order By Key

The function krsort() is like ksort() but sort the array in reverse order.

<?php
$colors = array(1=>"red", 5=>"orange", 4=>"blue", 2=>"green");
krsort($colors);
var_dump($colors);
// array(5=>"orange", 4=>"blue", 2=>"green", 1=>"red");
?>
Date:2019-10-01 02:46:17 From:www.Lautturi.com author:Lautturi