Search code examples
phpsessionstrcmpgettype

PHP strcmp is not returning the correct answer with session variable


I have a session variable $_SESSION['condition'], I know it is set because when I entered this:

echo $_SESSION['condition']." = "."Below Average";

It returns:

Below Average = Below Average

When I do a gettype() on the session variable it returns type "string".

Yet when I do strcmp() it returns: -34

I have also tried an IF statement with == rather than strcmp testing for equality AND an IF statement casting them both as strings and testing if they are equal with no luck.

Any reason why this could be?


Solution

  • There could be a whitespace or invisible character that is causing this problem with strcmp(). You can use trim() to help clean up strings and then use a literal equation operator, === to test for true equality. See below

    $condition = trim($_SESSION['condition']);
    
    if ($condition === 'Below Average') {
        echo 'True';
    } else {
        echo 'Nope!';
    }
    

    See if that helps at all.

    Also, you can use var_dump($_SESSION['condition']); to inspect the value.