Jump to: navigation, search

Php uksort

From w3cyberlearnings

Contents

PHP function uksort

This function sorts array key by using a user-defined function.

Syntax uksort

  • array: array input
  • callback: user-defined function
uksort(array,callback);

callback return

  • Return 0 when $a=$b
  • Return 1 when $a>$b
  • Return -1 when $a<$b

Note

The uksort function uses quicksort algorithm to sort.

Example 1

<?php

function sort2($v1, $v2) {
	if ($v1 == $v2) {
		return 0;
	} else if ($v1 > $v2) {
		return 1;
	} else {
		return -1;
	}
}

$list = array(
	 'aa' => 'banana',
	 'ab' => 'cling',
	 'bb' => 'soon',
	 'a1' => 32,
	 'a9' => 31,
	 'dd' => 'apple'
);

uksort($list, "sort2");

print_r($list);
?>

Output


Array
(
    [a1] => 32
    [a9] => 31
    [aa] => banana
    [ab] => cling
    [bb] => soon
    [dd] => apple
)

Example 2

<?php

function sort2($v1, $v2) {
	if ($v1 == $v2) {
		return 0;
	} else if ($v1 > $v2) {
		return 1;
	} else {
		return -1;
	}
}

$score = array(
	 30 => 'apple',
	 20 => 'king',
	 1 => 'yes',
	 3 => 'no',
	 10 => 'mother',
	 3 => 'father');

uksort($score, "sort2");

print_r($score);
?>

Output


Array
(
    [1] => yes
    [3] => father
    [10] => mother
    [20] => king
    [30] => apple
)

Related Links


Navigation
Web
SQL
MISC
References