How to compare two strings in version format? such that:
version_compare("2.5.1", "2.5.2") => -1 (smaller) version_compare("2.5.2", "2.5.2") => 0 (equal) version_compare("2.5.5", "2.5.2") => 1 (bigger) version_compare("2.5.11", "2.5.2") => 1 (bigger, eleven is bigger than two)
Answer: Use the PHP strcmp() function You can use the PHP strcmp() function to easily compare two strings. This function takes two strings str1 and str2 as parameters. The strcmp() function returns < 0 if str1 is less than str2 ; returns > 0 if str1 is greater than str2 , and 0 if they are equal.
The class doesn't provide a method to convert this type to a number, so it's not able to perform the comparison. However, it appears that this type has a method to convert to string. But PHP won't do a double conversion when performing the comparison.
PHP will compare alpha strings using the greater than and less than comparison operators based upon alphabetical order. In the first example, ai comes before i in alphabetical order so the test of > (greater than) is false - earlier in the order is considered 'less than' rather than 'greater than'.
From the PHP interactive prompt using the version_compare
function, built in to PHP since 4.1:
php > print_r(version_compare("2.5.1", "2.5.2")); // expect -1 -1 php > print_r(version_compare("2.5.2", "2.5.2")); // expect 0 0 php > print_r(version_compare("2.5.5", "2.5.2")); // expect 1 1 php > print_r(version_compare("2.5.11", "2.5.2")); // expect 1 1
It seems PHP already works as you expect. If you are encountering different behavior, perhaps you should specify this.
Also, you can use the PHP built-in function as below by passing an extra argument to the version_compare()
if(version_compare('2.5.2', '2.5.1', '>')) { print "First arg is greater than second arg"; }
Please see version_compare for further queries.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With