Reputation: 2427
Say I have an array
$ar = ['apples','blueberries','end','pears','dragonfruit','oranges','start','durian','lychee','rambutan','pineapple','end','start'];
I want the array in some order (lets say alphabetic order for this argument), but with the values 'end' on the tail and 'start' on the head of the array.
function cmp($a,$b) {
if ($a == $b) return 0;
if ($b === 'start') return 1;
if ($b === 'end') return -1;
return ($a < $b) ? -1 : 1;
}
usort($ar,"cmp");
echo implode(", ", $ar);
How do I sort so that values matching a specific value will end up at the head or tail of the array, but other values will sort based on other criteria (e.g. numeric, alpha, etc)
Upvotes: 1
Views: 63
Reputation: 577
Try this
$ar = ['apples','blueberries','end','pears','dragonfruit','oranges','start','durian','lychee','rambutan','pineapple','end','start', 'end', 'banana', 'yellow'];
function cmp($a, $b) {
if ($a === $b) {
return 0;
}
if ($a === 'start' || $b === 'end' ) {
return -1;
}
if( $b === 'start' || $a === 'end') {
return 1;
}
return ($a < $b) ? -1 : 1; }
usort($ar,"cmp");
echo implode(', ', $ar);
Hope this will help you
Upvotes: 1
Reputation: 6388
You can use array_diff
with sort
, array_push
and array_unshift
$elements = ['start','end'];//start & end elements array
$rest = array_diff($ar, $elements);
sort($rest);//Sorting of the rest items
array_push($rest, $elements[1]);//Push end element
array_unshift($rest, $elements[0]);//Push start element
You can use rsort($rest)
for descending order.
Live Example : https://3v4l.org/GnotC
Upvotes: 1
Reputation: 3476
Following is how your cmp function should be. Just a couple of if statements introduced.
function cmp($a, $b) {
if ($a === $b) {
return 0;
}
if ($a === 'start' ) {
return -1;
}
if( $b === 'start' ) {
return 1;
}
if ($a === 'end' ) {
return 1;
}
if ($b === 'end' ) {
return -1;
}
return ($a < $b) ? -1 : 1;
}
Upvotes: 0