Sorting arrays in PHP

This tutorial explains how to sort arrays in PHP. You will learn how to sort both regular arrays by their value and associative arrays by their key. You will also learn how to sort values and keys in an array in normal order (0-9,a-z) and reverse order (z-a,9-0). Watch the video below and then scroll down to see the sample code.

Sample PHP code:

  // sorting arrays by value (using sort function)
  $heroes = array("hulk","wonder woman","superman","iron man");
  sort($heroes); // or use rsort to reverse sort
  foreach($heroes as $value){
    echo "$value </br>";

  // sorting associative arrays by key (using ksort function)
  $characters = array("villain"=>"joker","hero"=>"batman");
  ksort($characters); // or use krsort to reverse sort by key
  foreach($characters as $key => $value){
    echo "The $key is $value </br>";