phpsortingusortalphabetical-sortnatsort

Find alphabetically first value using PHP


I am writing a sort function (using usort), and part of the operation I want to do there is determining which value comes first alphabetically. (This is only part of the operation, hence I'm not using natsort.) This means I have two strings for which I need to determine which is alphabetically first. Since this operation gets done in a loop, I want to have this done as simple as possible. One thing I could do is construct an array out of the two elements and use natsort on that. Is there a better approach, that does not involve constructing an array from the two values?

Edit: $a > $b seems to get basic cases right, though I'm not sure of how correct this behaves.


Solution

  • Use strcmp for that:

    From the documentation:

    Returns < 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are equal.

    Code:

    $str1 = 'foo';
    $str2 = 'bar';
    
    if(strcmp($str1, $str2) < 0) {
      echo '$str1 comes first';
    } elseif(strcmp($str1, $str2) > 0 ){
      echo '$str2 comes first';
    } 
    

    Output:

    $str2 comes first
    

    Demo!