Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare two version strings in PHP

Tags:

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) 
like image 311
ohho Avatar asked Dec 28 '12 09:12

ohho


People also ask

How do you check if two strings are the same in PHP?

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.

Will Comparison of string 15 and integer 15 works in PHP?

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.

How does PHP compare strings with comparison operators?

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'.


2 Answers

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.

like image 199
Charles Avatar answered Oct 21 '22 14:10

Charles


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.

like image 34
Kiran Tej Avatar answered Oct 21 '22 13:10

Kiran Tej