开发者

PHP - Divide sequence of numbers by decimal separation

I have a number that represents a software version (ex: 1.2.0.14) and I need to separate each number that is divided by a decimal and store each number as a separate variable.

Example:

Original number is 1.2.0.14

$current_version_major = 1;
$current_version_minor = 2;
$current_version_revision = 0;
$current_version_build = 14;

What would be the most 开发者_如何转开发efficient way to go about doing this?


I need to separate each number that is divided by a decimal and store each number as a separate variable.

The best you can do is to use explode and list like this:

list(
      $current_version_major,
      $current_version_minor,
      $current_version_revision,
      $current_version_build) = explode('.', $version_number);

More Info:

  • http://php.net/manual/en/function.explode.php
  • http://www.w3schools.com/PHP/func_array_list.asp


list($current_version_major,$current_version_minor,$current_version_revision,$current_version_build) = explode('.',$version);


If you don't actually need to store the version fields separately and just want to compare two versions, then version_compare is sometimes a good alternative:

switch (version_compare("1.2.0.14", "1.2.0.22")) {
    case -1:  // second version number is higher
    case  0:  // both identical
    case +1:  // second version is older
}

Besides supporting some text gimmicks (rc and beta suffixes) version_compare evaluates each part as integer, so that .14 is interpreted newer than .2. It also works with patch suffixes 1.0-2

It's even easier to use version_compare("2.0", "1.0", ">") to get a boolean result.


PHP has an explode function which returns you the elements as an array where delimiter will be "." (your 'decimal').


One way:

$version = explode(".", "1.2.0.14");

Now $version[0] contains "1" for major. $version[1] contains "2" for minor, $version[2] contains "0" for revision, and $version[3] contains "14" for build.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜