Search code examples
phpvariablescomparestrcmp

PHP: issue with comparing variables


I have two PHP variables that can either be empty (i.e. value="") or contain a name in the format Last, First with a comma and a space between the last and first name (e.g. Mouse, Mickey).

I would like to make a simple check here and say if a variable is not empty AND is equal to another then check a checkbox but this doesnt work. Can someone here show me what I am doing wrong (in the below example the checkbox should be checked) ?

My problem is that the checkbox always gets checked, even if the variables don't match.

Example:

$poc1 = "Mouse, Mickey"; // hard-coded for testing
$poc2 = "Mouse, Mickey"; // hard-coded for testing

<input type="checkbox" id="check2" name="Copy_POC" <?php if(($poc2 != "") && (strcmp($poc2,$poc1))) { echo "checked"; } ?> />

Many thanks for any help with this, Tim.


Solution

  • You need to look at the function signature for strcmp, and its return values:

    int strcmp ( string $str1 , string $str2 )
    

    So the function returns an int, but what kind of int? According to the manual:

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

    In other words: if both strings are equal, strcmp returns 0, which evaluates to false. What you should've written therefore is:

    strcmp($str1, $str2) !== 0
    

    This will evaluate to true if the 2 strings do not match. Of course, you only want to see the ckeckbox checked when the two strings don't match:

    if ($str1 != '' && strcmp($str1, $str2) === 0)
    {
        //checked
    }
    

    That ought to do it. Of course, this still relies on your calling functions to check these strings being equal. That doesn't really add up, though, and it might be a lot easier to just write:

    if ($str1 && $str1 === $str2)
    //an empty string is falsy + type & value check on 2 strings using === operator
    

    Note
    As you may already know, PHP is built on C, and therefore has a lot of C-like str* functions. Whenever you see a function like strcmp and strstr, check its return value. Like the C string.h functions, it often returns either a pointer (part of the string where substring is found, like strstr), or an integer (index/offset in string)...