PHP : Sort an array by key in Ascending or Descending order

In this tutorial learn how to sort an array using key in ascending or descending order in PHP.

function sortbyKeys($array, $direction = 'ASC')
    {
        $direction = (strtolower($direction) === 'desc') ? SORT_DESC : SORT_ASC;
        if ($direction === SORT_ASC) {
            ksort($array);
        } else {
            krsort($array);
        }

        return $array;
    }
      



TUTORIAL

<?php

$array = Array
(
    '3' => 10,
    '2' => 2,
    '5' => 'Nakiya',

);
      
      
/**
 * Sort an array by key.
 */
function sortbyKeys($array, $direction = 'ASC')
    {
        $direction = (strtolower($direction) === 'desc') ? SORT_DESC : SORT_ASC;
        if ($direction === SORT_ASC) {
            ksort($array);
        } else {
            krsort($array);
        }

        return $array;
    }
      

var_dump(sortbyKeys($array));

OUTPUT : DEMO

array(3) {
  [2]=>
  int(2)
  [3]=>
  int(10)
  [5]=>
  string(6) "Nakiya"
}

No comments:

Post a Comment

how to call ssh from vs code

 To call SSH from VS Code, you can use the built-in Remote Development extension. This extension allows you to open a remote folder or works...