PHP strcmp is not returning the correct answer with session variable

好久不见. 提交于 2019-12-11 23:36:30

问题


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?


回答1:


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.




回答2:


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!



来源:https://stackoverflow.com/questions/18796653/php-strcmp-is-not-returning-the-correct-answer-with-session-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!