PHP Array Sorting

Ang mga elemento ng array ay maaaring maayos sa abugado o numero, sa pagtaas o pagbaba.

PHP - Array Sorting Function

Sa Seksyon na ito, aaralin natin ang mga sumusunod na PHP array sorting function:

  • sort() - Pagtatalaga ng array sa pagtaas
  • rsort() - Pagtatalaga ng array sa pagbaba
  • asort() - Pagtatalaga ng array sa pagtaas ayon sa halaga
  • ksort() - Pagtatalaga ng array sa pagtaas ayon sa key
  • arsort() - Pagtatalaga ng array sa pagbaba ayon sa halaga
  • krsort() - Pagtatalaga ng array sa pagbaba ayon sa key

Sort ng array sa pagtaas - sort()

Ang mga halimbawa sa ibaba ay nagtatalaga ng abugado ang mga elemento ng array $cars sa talaan sa pagkasunod-sunod ng abugado:

Example

<?php
$cars=array("porsche","BMW","Volvo");
sort($cars);
?>

Running Instance

The following example sorts the elements of the array $numbers in ascending order by number:

Example

<?php
$numbers=array(3,5,1,22,11);
sort($numbers);
?>

Running Instance

Sort array in descending order - rsort()

The following example sorts the elements of the array $cars in descending order by letter:

Example

<?php
$cars=array("porsche","BMW","Volvo");
rsort($cars);
?>

Running Instance

The following example sorts the elements of the array $numbers in descending order by number:

Example

<?php
$numbers=array(3,5,1,22,11);
rsort($numbers);
?>

Running Instance

Sort array by value in ascending order - asort()

The following example sorts the associated array in ascending order by value:

Example

<?php
$age=array("Bill"=>"63","Steve"=>"56","Elon"=>"47");
asort($age);
?>

Running Instance

Sort array by key in ascending order - ksort()

The following example sorts the associated array in ascending order by key:

Example

<?php
$age=array("Bill"=>"63","Steve"=>"56","Elon"=>"47");
ksort($age);
?>

Running Instance

Sort array by value in descending order - arsort()

The following example sorts the associated array in descending order by value:

Example

<?php
$age=array("Bill"=>"63","Steve"=>"56","Elon"=>"47");
arsort($age);
?>

Running Instance

Sort array by key in descending order - krsort()

The following example sorts the associated array in descending order by key:

Example

<?php
$age=array("Bill"=>"63","Steve"=>"56","Elon"=>"47");
krsort($age);
?>

Running Instance

Complete PHP Array Reference Manual

For a complete reference manual of array functions, please visit our PHP Array Reference Manual.

This reference manual includes a brief description and usage examples of each function.