Jump to: navigation, search

Php uasort

From w3cyberlearnings

Contents

PHP function uasort

This function sorts array by using a user-defined function. Keep array keys or array index while it sorts the array value.

Syntax uasort

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

callback return

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

Note

The uasort 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;
	}
}

$score0 = array(
	 'a' => 1,
	 'b' => 2,
	 'c' => 16,
	 'd' => 23,
	 'e' => 1,
	 'f' => -1,
	 'h' => -9
);

$score1 = array(
	 'a' => 1,
	 'b' => 2,
	 'c' => 16,
	 'd' => 23,
	 'e' => 1,
	 'f' => -1,
	 'h' => -9
);

$score2 = array(
	 'a' => 1,
	 'b' => 2,
	 'c' => 16,
	 'd' => 23,
	 'e' => 1,
	 'f' => -1,
	 'h' => -9
);
// withou sort
print_r($score0);

// sort keep key and value
uasort($score0, "sort2");
// sort with key
uasort($score1, "sort2");
// sort with value
usort($score2, "sort2");


print_r($score0);
print_r($score1);
print_r($score2);
?>

Output

// without sorting
Array
(
    [a] => 1
    [b] => 2
    [c] => 16
    [d] => 23
    [e] => 1
    [f] => -1
    [h] => -9
)

// using uasort
// keep array key and value 
// sort by value
Array
(
    [h] => -9
    [f] => -1
    [e] => 1
    [a] => 1
    [b] => 2
    [c] => 16
    [d] => 23
)

// using uasort
// sort by key
Array
(
    [a] => 1
    [b] => 2
    [c] => 16
    [d] => 23
    [e] => 1
    [f] => -1
    [h] => -9
)
// using usort
// sort by value
// but the array key is not keep
Array
(
    [0] => -9
    [1] => -1
    [2] => 1
    [3] => 1
    [4] => 2
    [5] => 16
    [6] => 23
)

Example 2

<?php

$list = array('bc', 'ca', 'dd','aa', 'ab', 'bb');
print_r($list);
uasort($list, "strcmp");

print_r($list);
?>

Output

// without soring
Array
(
    [0] => bc
    [1] => ca
    [2] => dd
    [3] => aa
    [4] => ab
    [5] => bb
)
// using uasort 
// sort and keeps index as it is
Array
(
    [3] => aa
    [4] => ab
    [5] => bb
    [0] => bc
    [1] => ca
    [2] => dd
)

Related Links


Navigation
Web
SQL
MISC
References