skip to Main Content

I would like to sort an array of version strings in php.

Input would be something like this:

["2019.1.1.0", "2019.2.3.0", "2019.2.11.0", "2020.1.0.0", "2019.1.3.0", "2019.3.0.0"]

What is the easiest way to sort this? Sorting the strings as is does not work, because that would put the “2019.2.11.0” before “2019.2.3.0” and that is of course not what I want.

Result should be

["2019.1.1.0", "2019.1.3.0", "2019.2.3.0", "2019.2.11.0", "2019.3.0.0", "2020.1.0.0"]

2

Answers


  1. You are searching for a natural sort.

    $versions = ["2019.1.1.0", "2019.2.3.0", "2019.2.11.0", "2020.1.0.0", "2019.1.3.0", "2019.3.0.0"];
    $sorted = $versions;
    natsort($sorted);
    
    Array
    (
        [0] => 2019.1.1.0
        [4] => 2019.1.3.0
        [1] => 2019.2.3.0
        [2] => 2019.2.11.0
        [5] => 2019.3.0.0
        [3] => 2020.1.0.0
    )
    
    Login or Signup to reply.
  2. You should use version_compare function.

    This is how to use usort with version_compare.

    $a = ["2019.1.1.0", "2019.2.3.0", "2019.2.11.0", "2020.1.0.0", "2019.1.3.0", "2019.3.0.0"];
    
    usort($a, 'version_compare');
    
    var_dump($a);
    

    Result

    array(6) {
      [0]=>
      string(10) "2019.1.1.0"
      [1]=>
      string(10) "2019.1.3.0"
      [2]=>
      string(10) "2019.2.3.0"
      [3]=>
      string(11) "2019.2.11.0"
      [4]=>
      string(10) "2019.3.0.0"
      [5]=>
      string(10) "2020.1.0.0"
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search