This function is also usefull when working with multiple installations.
As php5.3+ will not have E_STRICT in the error_reporting anymore you can state:
<?php
ini_set('error_reporting', (version_compare(PHP_VERSION, '5.3.0', '<') ? E_ALL|E_STRICT : E_ALL));
?>
Giving you all the error error reporting you want...
version_compare
(PHP 4 >= 4.1.0, PHP 5)
version_compare — Compare deux chaînes de version au format des versions PHP
Description
version_compare() compare les deux versions de PHP standardisées. Cette fonction est pratique pour les programmes qui doivent vérifier la version de PHP qui les fait tourner.
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'. Ensuite, elle découpe les résultats, similairement à explode('.', $ver). 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 : dev < alpha = a < beta = b < RC < pl. 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 à la mode de PHP, à n'importe quel stade.
Liste de paramètres
- version1
-
Premier numéro de version.
- version2
-
Second numéro de version.
- operator
-
Si troisième argument optionnel operator est spécifié, il est possible de tester une relation particulière. Les opérateurs possibles sont : <, lt, <=, le, >, gt, >=, ge, ==, =, eq, !=, <>, ne.
Ce paramètre est sensible à la casse, aussi les valeurs doivent être en minuscule.
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 PHP utilisée pour exécuter le code.
Exemple #1 Exemple avec version_compare()
<?php
if (version_compare(PHP_VERSION, '6.0.0') === 1) {
echo 'J\'ai au moins la version 6.0.0 de PHP ; ma version : ' . PHP_VERSION . "\n";
}
if (version_compare(PHP_VERSION, '5.3.0') === 1) {
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\'utilise PHP 5 ; ma version : ' . PHP_VERSION . "\n";
}
if (version_compare(PHP_VERSION, '5.0.0', '<')) {
echo 'J\'utilise 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).
Voir aussi
- phpversion() - Retourne le numéro de la version courante de PHP
- php_uname() - Retourne les informations sur le système d'exploitation
- function_exists() - Indique si une fonction est définie
version_compare
30-Sep-2009 01:53
15-Aug-2009 11:47
Sometimes the code is forward compatible, for example when the code is compatible with all future PHP5 releases.
This function supports .x, for the above example it's : 5.x
<?php
function versionCompare($version1,$version2,$operand) {
$v1Parts=explode('.',$version1);
$version1.=str_repeat('.0',3-count($v1Parts));
$v2Parts=explode('.',$version2);
$version2.=str_repeat('.0',3-count($v2Parts));
$version1=str_replace('.x','.1000',$version1);
$version2=str_replace('.x','.1000',$version2);
return version_compare($version1,$version2,$operand);
}
?>
---
Sina Salek
http://sina.salek.ws/en/contact
06-Mar-2009 10:05
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;
}
?>
07-Mar-2008 07:54
<?php
// quick & dirty way to barricade your code during version transitions
assert('version_compare("5", PHP_VERSION, "<"); // requires PHP 5 or higher');
?>
30-Oct-2007 10:18
It should be noted that version_compare() considers 1 < 1.0 < 1.0.0 etc. I'm guessing this is due to the left-to-right nature of the algorithm.
30-Oct-2007 04:38
I know this is somewhat incomplete, but it did a fair enough job for what I needed. I was writing some code that needed done immediately on a server that was to be upgraded some time in the future. Here is a quick replacement for version_compare (without the use of the operator argument). Feel free to add to this / complete it.
<?php
function version_compare2($version1, $version2)
{
$v1 = explode('.',$version1);
$v2 = explode('.',$version2);
if ($v1[0] > $v2[0])
$ret = 1;
else if ($v1[0] < $v2[0])
$ret = -1;
else // Major ver are =
{
if ($v1[1] > $v2[1])
$ret = 1;
else if ($v1[1] < $v2[1])
$ret = -1;
else // Minor ver are =
{
if ($v1[2] > $v2[2])
$ret = 1;
else if ($v1[2] < $v2[2])
$ret = -1;
else
$ret = 0;
}
}
return $ret;
}
?>
11-Jun-2007 02:01
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', '>')
29-Sep-2004 11:28
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.
01-Jul-2004 04:40
Here's a wrapper which is more tolerant as far as order of arguments is considered:
<?php
function ver_cmp($arg1, $arg2 = null, $arg3 = null) {
static $phpversion = null;
if ($phpversion===null) $phpversion = phpversion();
switch (func_num_args()) {
case 1: return version_compare($phpversion, $arg1);
case 2:
if (preg_match('/^[lg][te]|[<>]=?|[!=]?=|eq|ne|<>$/i', $arg1))
return version_compare($phpversion, $arg2, $arg1);
elseif (preg_match('/^[lg][te]|[<>]=?|[!=]?=|eq|ne|<>$/i', $arg2))
return version_compare($phpversion, $arg1, $arg2);
return version_compare($arg1, $arg2);
default:
$ver1 = $arg1;
if (preg_match('/^[lg][te]|[<>]=?|[!=]?=|eq|ne|<>$/i', $arg2))
return version_compare($arg1, $arg3, $arg2);
return version_compare($arg1, $arg2, $arg3);
}
}
?>
It also uses phpversion() as a default version if only one string is present. It can make your code look nicer 'cuz you can now write:
<?php if (ver_cmp($version1, '>=', $version2)) something; ?>
and to check a version string against the PHP's version you might use:
<?php if (ver_cmp('>=', $version)) something; ?>
instead of using phpversion().
22-Jun-2004 06:50
[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
}
?>
23-May-2004 08:18
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).
