version_compare

(PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8)

version_compareCompare deux chaînes de version au format des versions PHP

Description

version_compare(string $version1, string $version2, ?string $operator = null): int|bool

version_compare() compare les deux versions de PHP standardisées.

version_compare() remplace dans un premier temps _, - et + par un point (.) dans les chaînes de version et insère aussi des points avant et après tout caractère non-numérique pour que, par exemple, '4.3.5RC1' devienne '4.3.5.RC.1'. Puis, elle compare les morceaux en allant de gauche à droite. Si une part contient des caractères alphabétiques, ils sont gérés dans l'ordre suivant : any string not found in this list < dev < alpha = a < beta = b < RC = rc < # < pl = p. De cette façon, il est possible de comparer non seulement des versions de différents niveaux, comme '4.1' et '4.1.2', mais aussi des versions de développement de PHP, à n'importe quel stade.

Liste de paramètres

version1

Premier numéro de version.

version2

Second numéro de version.

operator

Un opérateur optionnel. Les opérateurs possibles sont : <, lt, <=, le, >, gt, >=, ge, ==, =, eq, !=, <>, ne respectivement.

Ce paramètre est sensible à la casse, les valeurs doivent donc être en minuscules.

Valeurs de retour

Par défaut, version_compare() retourne -1 si la première version est inférieure à la seconde, 0 si elles sont égales, et 1 si la seconde est inférieure à la première.

Lorsque l'on utilise le paramètre optionnel operator, la fonction retourne true si la relation est celle spécifiée par l'opérateur, false sinon.

Exemples

Les exemples ci-dessous utilisent la constante PHP_VERSION, sachant qu'elle contient la valeur de la version de PHP utilisée pour exécuter le code.

Exemple #1 Exemple avec version_compare()

<?php
if (version_compare(PHP_VERSION, '7.0.0') >= 0) {
echo
'J\'ai au moins la version 7.0.0 de PHP ; ma version : ' . PHP_VERSION . "\n";
}

if (
version_compare(PHP_VERSION, '5.3.0') >= 0) {
echo
'J\'ai au moins la version 5.3.0 de PHP ; ma version : ' . PHP_VERSION . "\n";
}

if (
version_compare(PHP_VERSION, '5.0.0', '>=')) {
echo
'J\'ai au moins la version 5.0.0 de PHP ; ma version : ' . PHP_VERSION . "\n";
}

if (
version_compare(PHP_VERSION, '5.0.0', '<')) {
echo
'J\'utilise encore PHP 4 ; ma version : ' . PHP_VERSION . "\n";
}
?>

Notes

Note:

La constante PHP_VERSION contient la version courante de PHP.

Note:

Notez que les versions intermédiaires, comme 5.3.0-dev, sont considérées comme inférieures à leurs versions finales (telle que 5.3.0).

Note:

Les chaînes spéciales de version comme alpha et beta sont sensibles à la casse. Les chaînes de version issues de sources arbitraires qui n'adhère pas au standard PHP doivent être mises en minuscule en utilisant la fonction strtolower() avant d'appeler la fonction version_compare().

Voir aussi

add a note add a note

User Contributed Notes 8 notes

up
18
eric at themepark dot com
19 years ago
[editors note]
snipbit fixed after comment from Matt Mullenweg

--jm
[/editors note]

so in a nutshell... I believe it works best like this:

<?php
if (version_compare(phpversion(), "4.3.0", ">=")) {
 
// you're on 4.3.0 or later
} else {
 
// you're not
}
?>
up
9
mindplay.dk
11 years ago
This little script can perhaps help you understand version comparison a little better - the output is displayed in the comment at the top. Tweak the list of versions if you need more examples...

<?php

#      1 lt 1.0
#    1.0 lt 1.01
#   1.01 eq 1.1
#    1.1 lt 1.10
#   1.10 gt 1.10b
#  1.10b lt 1.10.0

header('Content-type: text/plain');

$versions = array(
 
'1',
 
'1.0',
 
'1.01',
 
'1.1',
 
'1.10',
 
'1.10b',
 
'1.10.0',
);

$comps = array(
-
1 => 'lt',
 
0 => 'eq',
 
1 => 'gt'
);

foreach (
$versions as $version) {
  if (isset(
$last)) {
   
$comp = version_compare($last, $version);
    echo
str_pad($last,8,' ',STR_PAD_LEFT) . " {$comps[$comp]} {$version}\n";
  }
 
$last = $version;
}

?>
up
10
insid0r at yahoo dot com
15 years ago
Since this function considers 1 < 1.0 < 1.0.0, others might find this function useful (which considers 1 == 1.0):

<?php
//Compare two sets of versions, where major/minor/etc. releases are separated by dots.
//Returns 0 if both are equal, 1 if A > B, and -1 if B < A.
function version_compare2($a, $b)
{
   
$a = explode(".", rtrim($a, ".0")); //Split version into pieces and remove trailing .0
   
$b = explode(".", rtrim($b, ".0")); //Split version into pieces and remove trailing .0
   
foreach ($a as $depth => $aVal)
    {
//Iterate over each piece of A
       
if (isset($b[$depth]))
        {
//If B matches A to this depth, compare the values
           
if ($aVal > $b[$depth]) return 1; //Return A > B
           
else if ($aVal < $b[$depth]) return -1; //Return B > A
            //An equal result is inconclusive at this point
       
}
        else
        {
//If B does not match A to this depth, then A comes after B in sort order
           
return 1; //so return A > B
       
}
    }
   
//At this point, we know that to the depth that A and B extend to, they are equivalent.
    //Either the loop ended because A is shorter than B, or both are equal.
   
return (count($a) < count($b)) ? -1 : 0;
}
?>
up
2
Bob Ray
8 years ago
Note that both leading and trailing spaces on your version numbers can break version_compare().

Tested on PHP 5.6.8:
<?php
echo  "\nShould be 0";
echo
"\n '1.0.0-pl' vs. '1.0.0-pl'  ---> " . version_compare('1.0.0-pl', '1.0.0-pl');
echo
"\n '1.0.0-pl' vs. ' 1.0.0-pl' ---> " . version_compare('1.0.0-pl', ' 1.0.0-pl');
echo
"\n ' 1.0.0-pl' vs. '1.0.0-pl' ---> " . version_compare(' 1.0.0-pl', '1.0.0-pl');
echo
"\n '1.0.0-pl' vs. '1.0.0-pl ' ---> " . version_compare('1.0.0-pl', '1.0.0-pl ');
echo
"\n '1.0.0-pl ' vs. '1.0.0-pl' ---> " . version_compare('1.0.0-pl ', '1.0.0-pl');

echo
"\n\nShould be 1";
echo
"\n '1.1.1-pl' vs. '1.0.0-pl'  ---> " . version_compare('1.1.1-pl', '1.0.0-pl');
echo
"\n ' 1.1.1-pl' vs. '1.0.0-pl' ---> " . version_compare(' 1.1.1-pl', '1.0.0-pl');

echo
"\n\nShould be -1";
echo
"\n '1.0.0-pl' vs. '1.1.1-pl'  ---> " . version_compare('1.0.0-pl', '1.1.1-pl');
echo
"\n '1.0.0-pl' vs. ' 1.1.1-pl' ---> " . version_compare('1.0.0-pl', ' 1.1.1-pl');

   
/* Output
Should be 0
'1.0.0-pl' vs. '1.0.0-pl'  ---> 0
'1.0.0-pl' vs. ' 1.0.0-pl' ---> 1
' 1.0.0-pl' vs. '1.0.0-pl' ---> -1
'1.0.0-pl' vs. '1.0.0-pl ' ---> 1
'1.0.0-pl ' vs. '1.0.0-pl' ---> -1

Should be 1
'1.1.1-pl' vs. '1.0.0-pl'  ---> 1
' 1.1.1-pl' vs. '1.0.0-pl' ---> -1

Should be -1
'1.0.0-pl' vs. '1.1.1-pl'  ---> -1
'1.0.0-pl' vs. ' 1.1.1-pl' ---> 1
    */
up
2
rogier
12 years ago
Please note that supplying an operator that is not listed (e.g. ===), this function returns NULL instead of false.

Tested on PHP5.3.0, Win32
up
3
opendb at iamvegan dot net
16 years ago
Something that may trip some folks up, but is useful to mention is that the following version comparison does not work quite as I expected:
    version_compare('1.0.1', '1.0pl1', '>')

However, its quite easy to get working:
    version_compare('1.0.1', '1.0.0pl1', '>')
up
3
arnoud at procurios dot nl
19 years ago
If you're careful, this function actualy works quite nicely for comparing version numbers from programs other than PHP itself. I've used it to compare MySQL version numbers. The only issue is that version_compare doesn't recognize the 'gamma' addition that mysql uses as being later than 'alpha' or 'beta', because the latter two are treated specially. If you keep this in mind though, you should have no problems.
up
0
sam at wyvern dot non-spammers-remove dot com dot au
19 years ago
Actually, it works to any degree:

<?php
version_compare
('1.2.3.4RC7.7', '1.2.3.4RC7.8')
version_compare('8.2.50.4', '8.2.52.6')
?>

will both give -1 (ie the left is lower than the right).
To Top