PHP strcmp is not returning the correct answer with session variable

1.4k views Asked by At

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?

2

There are 2 answers

3
Rottingham On BEST ANSWER

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.

0
Amal Murali On

strcmp() function (usually) returns the difference of the first different character between the strings.

So, if there's a difference between your strings anywhere, strcmp() stops there and returns the difference between the ASCII values of the two characters.

As Barmar pointed out in the comments, the difference between a space and B is -34 and I believe this is the case.

This can be confirmed by:

$v1 = ord(' ') - ord('B');
$v2 = strcmp('B', ' ');

if($v1 == $v2) {
    echo 'True';
}

Output:

True

Demo!

To make sure this doesn't happen, you can either use trim() as Rottingham suggested, or a regular expression to strip out all the unwanted characters.

For replacing all the whitespace:

$string = preg_replace('/\s+/', ' ', $string); 

To remove the whitespace from beginning and end:

$string = trim($string);

Hope this helps!