downloads | documentation | faq | getting help | mailing lists | licenses | wiki | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

zend_logo_guid> <sys_get_temp_dir
[edit] Last updated: Fri, 23 Mar 2012

view this page in

version_compare

(PHP 4 >= 4.1.0, PHP 5)

version_comparePHP standardına uygun hale getirilmiş iki sürüm numarası dizgesini karşılaştırır

Açıklama

mixed version_compare ( string $sürüm1 , string $sürüm2 [, string $işleç ] )

version_compare() işlevi PHP standardına uygun hale getirilmiş iki sürüm numarası dizgesini karşılaştırır. PHP'nin sadece belli bir sürümü ile çalışabilecek betikler yazıyorsanız bu işleve ihtiyacınız olacaktır.

İşlev önce _, - ve + karakterlerini birer nokta . ile değiştirir, ardından numara olmayan dizgeciklerin önüne ve ardına birer nokta konur. Örneğin, '4.3.2RC1' dizgesi '4.3.2.RC.1' haline gelir. Elde edilen dizge, explode('.', $sürüm) kullanılmışçasına bileşenlerine ayrıldıktan sonra her bileşen soldan sağa karşılaştırılır. Bileşenlerin içerdiği özel sürüm dizgeleri şu sıralamaya göre ele alınırlar: bu listede olmayan bir dizge < dev < alpha = a < beta = b < RC = rc < # < pl = p. Bu yöntemle, '4.1' ve '4.1.2' gibi farklı seviyelerden sürümler karşılaştırabileceği gibi geliştirme sürümlerinin karşılaştırılması için de kullanılabilir.

Değiştirgeler

sürüm1

İlk sürüm numarası.

sürüm2

İkinci sürüm numarası.

işleç

İsteğe bağlı bu değiştirge ile sürümler arasında belli ilişkileri sınayabilirsiniz. Olası işleçler şunlardır: <, lt, <=, le, >, gt, >=, ge, ==, =, eq, !=, <>, ne.

Bu değiştirge harf büyüklüğüne duyarlıdır, yani değerlerin hepsi küçük harfli olmalıdır.

Dönen Değerler

Öntanımlı olarak, version_compare() işlevi, birinci sürüm ikincisinden küçükse -1, büyükse 1, eşitlerse 0 döndürür.

İsteğe bağlı işleç değiştirgesi kullanılırsa ve sürümler arasında belirtilen ilişki varsa TRUE aksi takdirde FALSE döner.

Örnekler

Aşağıdaki örnekte, kodu çalıştıran PHP sürümüne içermesi nedeniyle PHP_VERSION sabiti kullanılmıştır.

Örnek 1 - version_compare() örnekleri

<?php
if (version_compare(PHP_VERSION'6.0.0') === 1) {
    echo 
'PHP sürümüm en azından 6.0.0, gerçek sürüm: ' PHP_VERSION "\n";
}

if (
version_compare(PHP_VERSION'5.3.0') === 1) {
    echo 
'PHP sürümüm en azından 5.3.0, gerçek sürüm: ' PHP_VERSION "\n";
}

if (
version_compare(PHP_VERSION'5.0.0''>')) {
    echo 
'PHP 5 kullanıyorum, gerçek sürüm: ' PHP_VERSION "\n";
}

if (
version_compare(PHP_VERSION'5.0.0''<')) {
    echo 
'PHP 4 kullanıyorum, gerçek sürüm: ' PHP_VERSION "\n";
}
?>

Notlar

Bilginize:

PHP_VERSION sabiti kullanılan PHP'nin sürüm numarasını içerir.

Bilginize:

5.3.0-dev gibi ön dağıtım sürümleri için, alt sürümün, ulaşacakları asıl sürümün numarası (PHP 5.3.0) olduğu varsayılır.

Ayrıca Bakınız

  • phpversion() - Çalışan PHP'nin sürümünü döndürür
  • php_uname() - PHP'nin çalıştığı işletim sistemi hakkında bilgi döndürür
  • function_exists() - Eğer işlev tanımlanmış ise TRUE döndürür



zend_logo_guid> <sys_get_temp_dir
[edit] Last updated: Fri, 23 Mar 2012
 
add a note add a note User Contributed Notes version_compare
rogier 30-Nov-2011 01:43
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
Steve Kamerman 24-Jun-2011 06:07
I know I'm splitting hairs here, but if you're OCD like me

(version_compare(PHP_VERSION, '5.3.0') >= 0)

is about 13% faster than

(version_compare(PHP_VERSION, '5.3.0', '>=')

<?php
$count
= 200000;
$start = microtime(true);
for(
$i=0;$i<$count;$i++) (version_compare(PHP_VERSION, '5.3.0') >= 0);
echo
"Real Operator: ".(microtime(true) - $start)."\n";
$start = microtime(true);
for(
$i=0;$i<$count;$i++) (version_compare(PHP_VERSION, '5.3.0', '>='));
echo
"String Operator: ".(microtime(true) - $start)."\n";
?>
loaded67 at hotmail dot com 29-Sep-2009 10:53
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...
Sina Salek 14-Aug-2009 08: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
insid0r at yahoo dot com 06-Mar-2009 06: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;
}
?>
Niraj Bhawnani 09-Feb-2009 11:10
This function also works nicely when comparing IP addresses :)
bishop 07-Mar-2008 03:54
<?php
// quick & dirty way to barricade your code during version transitions
assert('version_compare("5", PHP_VERSION, "<"); // requires PHP 5 or higher');
?>
Rickard Andersson 30-Oct-2007 07: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.
Jonathon dot Reinhart at gmail dot com 30-Oct-2007 01: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;
}
?>
opendb at iamvegan dot net 10-Jun-2007 11: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', '>')
arnoud at procurios dot nl 28-Sep-2004 08: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.
mina86 at tlen dot pl 30-Jun-2004 01: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().
eric at themepark dot com 21-Jun-2004 03: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
}
?>
sam at wyvern dot non-spammers-remove dot com dot au 23-May-2004 05: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).

 
show source | credits | stats | sitemap | contact | advertising | mirror sites