Reputation: 31
I would like to increment version number $numero1 = "1.0.1"
by the following ruleset.
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?
Upvotes: 2
Views: 2371
Reputation: 3323
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 );
Upvotes: 6
Reputation: 2707
I think this one works smoother without too many if's/loops:
$a = '1.9.9';
$a = str_replace('.', '', $a) + 1;
$a = implode('.', str_split($a));
echo $a;
Basically convert it to a number, increment then convert it back.
The only drawback is that the first integer has to be >= 1
. So 0.0.1
won't work. I am assuming it would always be >= 1.0.0
from what you posted.
Upvotes: 6