+ 2

How does function strcmp() works in php

For this moment I do not understand in which cases I can use function strcmp() and how it actually works. Here we have several cases with different ways how this function works. Case 1: $a = ‘phh’; $b = ‘pip’; echo strcmp($a, $b); // In this case we will get result -1. As I understand it starts to compare letter by letter and when function found difference it starts to compare two values. In this case first difference found in second letter $a[1] is “h” and $b[1] is “i”. Difference between this number is 1 as letter “i” goes after letter “h”. Minus sign we get because $a < $b. Also this function stop to compare after the first difference is found. Case 2: $a = ‘php’; $b = ‘phpphp’; echo strcmp($a, $b); // In this case we will get result -3. As I understand first function strcmp() as in first case starts to compare letter by letter and found that first 3 letters of two strings are similar, but as length of string $b is longer then string $a it start count the difference of symbols? $b > $a for 3 symbol so we get result -3.

19th Nov 2020, 1:01 AM
Vadims Lukjanskis
Vadims Lukjanskis - avatar
1 Answer
+ 1
There are 3 meaningful results. 0, less than 0, greater than 0. Those results correspond with 0: a === b < 0: a < b > 0: a > b Try to ignore the -3 vs -1 result for strcmp($a, $b) because those values both mean the same thing. Either way, a < b. Without seeing the implementation it is hard to see why the -1 and -3 are different because all the documentation says is the 3 cases above. This official documentation has more details on the function: https://www.php.net/manual/en/function.strcmp.php
19th Nov 2020, 8:44 PM
Josh Greig
Josh Greig - avatar