Search code examples
phpstringcomparisonalphanumericnatural-sort

Naturally compare two alphanumeric strings to see if one is less than the other


I have 2 strings:

$string_1 = 'c5';
$string_2 = 'c6';

And I want to check if $string_2 comes after or before $string_1 if both were ordered in an alphabetic order.

So in the examples above, $string_2 comes after $string_1. But if value of $string_2 was c2, then it would become before $string_1...

What's a solid approach to do this check with a boolean result?

What I've tried so far

I can add strings into an array, order array by alphabetic order, and then check which whether if $string_2 as $key value 0 or 1.

EDIT

Note that c2 should come before c11.


Solution

  • Make the array, sort it, using natsort, and get the name of the variable with a less value

    $string_1 = 'c5';
    $string_2 = 'c6';
    $res = compact('string_1', 'string_2'); // ['string_1' => 'c5', 'string_2' => 'c6']
    natsort($res);
    echo key($res); // name of variable with less value  
    

    demo