The version_compare Function

The version_compare function compares two strings containing version numbers, and returns the comparison result. It takes three parameters: two version strings and an optional comparison operator. Returns -1, 0, or 1 if the first version is less than, equal to, or greater than the second, respectively.

Syntax

phpversion_compare(string $version1, string $version2, string $operator = null);

Example

Compare two versions:

php<?php
  $res = version_compare('1.2.3', '1.2.4');
  echo $res;
?>

Code execution result:

php-1

Example

Check if the version meets the minimum requirements:

php<?php
  if (version_compare(PHP_VERSION, '8.0.0', '>=')) {
    echo 'PHP version is suitable';
  } else {
    echo 'PHP 8.0.0 or higher is required';
  }
?>

Code execution result (example):

php'PHP version is suitable'

Example

Compare versions with alpha and beta releases:

php<?php
  $res = version_compare('1.0.0b', '1.0.0a');
  echo $res;
?>

Code execution result:

php1

See Also

  • the phpversion function,
    which returns the current PHP version