Jump to: navigation, search

Php usort

From w3cyberlearnings

Contents

PHP function usort

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

Syntax usort

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

callback return

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

Note

The usort 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('bc', 'ca', 'dd','aa', 'ab', 'bb');

usort($list, "sort2");

print_r($list);
?>

Output


Array
(
    [0] => aa
    [1] => ab
    [2] => bb
    [3] => bc
    [4] => ca
    [5] => dd
)

Example 2

<?php

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

$score = array(30, 20, 1, 3, 10, 3);
usort($score, "sort2");
print_r($score);
?>

Output


Array
(
    [0] => 1
    [1] => 3
    [2] => 3
    [3] => 10
    [4] => 20
    [5] => 30
)

Example 3

<?php

$list = array('bc', 'ca', 'dd','aa', 'ab', 'bb');

usort($list, "strcmp");

print_r($list);
?>

Output


Array
(
    [0] => aa
    [1] => ab
    [2] => bb
    [3] => bc
    [4] => ca
    [5] => dd
)

Example 4

<?php

$myArray = array(1, 19, 18, 12, 56);

function compare($a, $b) {
    echo "Comparing $a to $b\n";
    if ($a == $b) return 0;
    return ($a < $b) ? -1 : 1;
}

usort($myArray,"compare");
print_r($myArray);
?>

Output

sophal@test1:~$ php sort.php
Comparing 18 to 19
Comparing 56 to 18
Comparing 12 to 18
Comparing 1 to 18
Comparing 12 to 1
Comparing 56 to 19
Array
(
    [0] => 1
    [1] => 12
    [2] => 18
    [3] => 19
    [4] => 56
)

Example 6

<?php

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

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

usort($list, "sort2");

print_r($list);
?>

Output


Array
(
    [0] => apple
    [1] => banana
    [2] => cling
    [3] => soon
    [4] => 31
    [5] => 32
)

Related Links


Navigation
Web
SQL
MISC
References