Skip to content

Instantly share code, notes, and snippets.

@hello-josh
Last active August 29, 2015 14:27
Show Gist options
  • Save hello-josh/fb41986a9db511204f59 to your computer and use it in GitHub Desktop.
Save hello-josh/fb41986a9db511204f59 to your computer and use it in GitHub Desktop.
An alternative idea to the <=> T_SPACESHIP from https://wiki.php.net/rfc/combined-comparison-operator
<?php
/**
* User Getter Sort - Sorts an array using a user defined getter function.
*
* An imaginary user defined sort alternative where you pass a function that
* returns the data that should be used to determine sort order
* @param array &$array Array to sort in place
* @param Callable $itemfunc The callable that receives the array
* item and returns the value that should
* be used for sorting
*/
function ugsort(&$array, $itemfunc = function($item) {return $item});
// rewrite examples from https://wiki.php.net/rfc/combined-comparison-operator using ugsort
// Use case #1 Sort by last name
usort($data, function ($left, $right) {
return $left[1] <=> $right[1];
});
// ugsort version
ugsort($data, function ($item) {
return $item[1];
});
// sort by arrays
function order_func($a, $b) {
return [$a->x, $a->y, $a->foo] <=> [$b->x, $b->y, $b->foo];
}
usort(&$array, 'order_func');
// ugsort version
ugsort($data, function ($item) {
return [$item->x, $item->y, $item->foo];
});
@hello-josh
Copy link
Author

$itemfunc works similarly to cmp= in python's sorted

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment