Here is an example of a function that condenses your switch statement. Warning untested but should do the trick.
function photoStort(array &$photos, $key, $order) {
if ($order !== 'desc' && $order !== 'asc') {
return false;
}
usort($photos, function($a, $b) use ($key, $order) {
$t1 = $a[$key];
$t2 = $b[$key];
if (is_string($t1) && is_string($t2)) {
if ($order === 'asc') {
return strcmp($t1, $t2);
} else {
return strcmp($t2, $t1);
}
} elseif (is_int($t1) && is_int($t2)) {
if ($order === 'asc') {
return $t1 - $t2;
} else {
return $t2 - $t1;
}
} else {
trigger_error('Invalid type in photoSort!', E_WARNING);
}
});
}
$photos = array(/* Photos */);
//ex 1
photoSort($photos, 'photoname', 'asc');
//ex 2
photoSort($photos, 'id', 'desc');
PHP 5.2 solution
function usortCallback($a, $b, $key, $order) {
$t1 = $a[$key];
$t2 = $b[$key];
if (is_string($t1) && is_string($t2)) {
if ($order === 'asc') {
return strcmp($t1, $t2);
} else {
return strcmp($t2, $t1);
}
} elseif (is_int($t1) && is_int($t2)) {
if ($order === 'asc') {
return $t1 - $t2;
} else {
return $t2 - $t1;
}
} else {
trigger_error('Invalid type in photoSort!', E_WARNING);
}
}
function photoSort(array &$photos, $key, $order) {
if ($order !== 'desc' && $order !== 'asc') {
return false;
}
usort($photos, create_function('$a, $b', 'return usortCallback($a, $b, "' . $key . '", "' . $order . '");'));
}