Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the highest version number / tag in PHP

Tags:

php

Because the Bitbucket API doesn't provide a method to get the latest tag for a repository I find myself having to get it from an array of all tags.

How do you do it?

I have tried max but it doesn't work for certain numbers e.g.

max(['1.0.8', '1.0.9', '1.0.10']);

returns '1.0.9'.

I know the tags will only ever be three numbers a.b.c they won't have other semver accepted strings like alpha etc. because of the way we do tags for our repos.

So how do you do it?

like image 919
mattl Avatar asked Feb 24 '16 10:02

mattl


1 Answers

$versions = ['1.0.8', '1.0.9', '1.0.10'];
usort($versions, 'version_compare');
echo end($versions);

See http://php.net/version_compare

If you don't feel like modifying the array:

echo array_reduce($versions, function ($highest, $current) {
    return version_compare($highest, $current, '>') ? $highest : $current;
});
like image 141
deceze Avatar answered Nov 07 '22 16:11

deceze