PHP 8.5.0 Alpha 1 available for testing

Voting

: max(nine, six)?
(Example: nine)

The Note You're Voting On

brian dot short at gmail dot com
15 years ago
If you need to periodically sort by grades (A, A+, D-, etc.), here is a compare function that compares strings by the case-insensitive method, unless it finds a grade, in which case it correctly sorts by putting "plus" grades first, unmarked grades second, and "minus" grades last.

<?php
function cmp($a, $b)
{
$a = preg_replace('@^(a|an|the) @', '', $a);
$b = preg_replace('@^(a|an|the) @', '', $b);

//special code for grades
if (strpos( $a, "+") !== false || strpos( $b, "+") !== false ||
strpos( $a, "-") !== false || strpos( $b, "-") !== false ){

$substrA = substr($a, 0, 1);
$substrB = substr($b, 0, 1);

$modifierA = (strlen($a) == 2) ? substr($a, 1, 1) : "";
$modifierB = (strlen($b) == 2) ? substr($b, 1, 1) : "";

if (
$substrA == $substrB){
//figure out plusses and minuses.
if ($modifierA == "+"){
return -
1;
} else if (
$modifierB == "+"){
return
1;
}

if (
$modifierA == "-"){
return
1;
} else if (
$modifierB == '-'){
return -
1;
}
} else {
return
strcasecmp($a, $b);
}

}
return
strcasecmp($a, $b);
}

$grades = array(
"C+" => 13 ,
"C" => 10 ,
"D+" => 8 ,
"B+" => 7 ,
"C-" => 6 ,
"A-" => 5 ,
"F" => 5 ,
"B" => 4 ,
"B-" => 4 ,
"D" => 3 ,
"D-" => 3 ,
"A+" => 1
);

uksort($grades, "cmp");
?>

result: Array
(
[A+] => 1
[A-] => 5
[B+] => 7
[B] => 4
[B-] => 4
[C+] => 13
[C] => 10
[C-] => 6
[D+] => 8
[D] => 3
[D-] => 3
[F] => 5
)

<< Back to user notes page

To Top