In this tutorial learn how to sort an array using key in ascending or descending order in PHP.
TUTORIAL
OUTPUT : DEMO
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