Search code examples
phpstrcmp

PHP strcmp not giving correct output


I am comparing two string by strcmp(1,2) and i am getting "-1 " insted of 1 my code is below

  <?php
    echo strcmp(1,2);
   ?>

output:-1

enter image description here

please let me know why i am getting -1 for false and how to handle it ?


Solution

  • 1 is less than 2, strcmp is defined as returning:

    Returns < 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are equal.

    Thus the behaviour is expected.


    Note the following caveat:

    If you rely on strcmp for safe string comparisons, both parameters must be strings, the result is otherwise extremely unpredictable. For instance you may get an unexpected 0, or return values of NULL, -2, 2, 3 and -3.

    From a comment on the documentation page for strcmp.


    PHP is full of this sort of unexpected behaviour. In your situation, I would ensure both arguments were cast as strings to avoid any confusion:

    $first = 1;
    $second = 2;
    echo strcmp((string)$first, (string)$second);