2

I am trying to implement a function that will sort an array of strings in lexical order (case-insensitive). But with one exception: if the string is equal to, let's say, "bingo!" put this line on top.

I made some function which works well on the given test data. But I'm not sure I don't fool myself with special case. Please check me.

<?php

$a = [
    'alfa', 
    'beta',
    'gama',
    'sigma',
    'foo',
    'bar',
    'bingo!',
];

usort($a, function ($a, $b) {
    $cmp = strcasecmp($a, $b);
    return $cmp == 0
    ? 0
    : (strcasecmp($a, 'bingo!') == 0
            ? -1000
            : (
            strcasecmp($b, 'bingo!') == 0
            ? 1000
            : $cmp
            )
    );
});

var_export($a);
artoodetoo
  • 918
  • 10
  • 55
  • 3
    Looks correct to me. I wouldn't use all the nested conditional expressions, but that's just a style decision. – Barmar Feb 10 '20 at 15:19

2 Answers2

1

You can try this way :

$reserved_keyword = 'bingo!';

$a = [
    'alfa', 
    'beta',
    'gama',
    'sigma',
    'foo',
    'bar',
    'bingo!',
];

$reserved_keyword_key = array_search($reserved_keyword , $a);

unset($a[$reserved_keyword_key]);

natcasesort($a);

array_unshift($a,$reserved_keyword );

var_dump($a);

To use as a function :

function order($array , $reserved_keyword){
  unset($array[array_search($reserved_keyword , $array)]);
  natcasesort($array);
  array_unshift($array,$reserved_keyword );
  return $array;
}

The result :

array(7) {
  [0]=>
  string(6) "bingo!"
  [1]=>
  string(4) "alfa"
  [2]=>
  string(3) "bar"
  [3]=>
  string(4) "beta"
  [4]=>
  string(3) "foo"
  [5]=>
  string(4) "gama"
  [6]=>
  string(5) "sigma"
}
Yassine CHABLI
  • 3,459
  • 2
  • 23
  • 43
1

A solution with usort:

$onTop = 'bingo!';

$array = [
   'alfa', 
   'beta',
   'gama',
   'sigma',
   'foo',
   'bar',
   'bingo!',   
];

usort($array,function($a,$b) use($onTop){
  $r = ($b == $onTop) <=> ($a == $onTop);
  return $r==0 ? strnatcasecmp($a,$b) : $r;
});

var_export($array);

Result:

array (
  0 => "bingo!",
  1 => "alfa",
  2 => "bar",
  3 => "beta",
  4 => "foo",
  5 => "gama",
  6 => "sigma",
)
jspit
  • 7,276
  • 1
  • 9
  • 17