Quinn Humphreys Quinn Humphreys - 3 years ago 156
PHP Question

PHP how to increment version number under certain requirements

I would like to increment this number

$numero1 = "1.0.1"
by the following requirements.


  1. Increment the last number (the one after the second period).

  2. If the incremented number is greater than 9 then set to 0 and increment the second number.

  3. If the second number is also greater than 9 (after incrementing) then set to 0 and increment the first number.



So what I did is
$numerosumado = $numero1 + 1
but it's not working because of the dots. So my question is how do I do it?

Answer Source

Note: This is just one way out of many...

For further explanations see the comments in this working snippet.

<?php
$numero1 = "1.9.9";
$numerosumado = explode( ".", $numero1 ); // array( "1", "9", "9" )
if ( ++$numerosumado[2] > 9 ) { // if last incremented number is greater than 9 reset to 0
    $numerosumado[2] = 0;
    if ( ++$numerosumado[1] > 9 ) { // if second incremented number is greater than 9 reset to 0
        $numerosumado[1] = 0;
        ++$numerosumado[0]; // incremented first number
    }
}
$numerosumado = implode( ".", $numerosumado ); // implode array back to string

Hint: incrementing a numeric string such as "1" or "0.9" will automatically change the type to integer or float and increment as expected.


Edit:

This solution is a bit more elegant.

<?php
$version = "9.9.9";
for ( $new_version = explode( ".", $version ), $i = count( $new_version ) - 1; $i > -1; --$i ) {
    if ( ++$new_version[ $i ] < 10 || !$i ) break; // break execution of the whole for-loop if the incremented number is below 10 or !$i (which means $i == 0, which means we are on the number before the first period)
    $new_version[ $i ] = 0; // otherwise set to 0 and start validation again with next number on the next "for-loop-run"
}
$new_version = implode( ".", $new_version );
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download