PHP String Comparison Not Working
I am having an issue with PHP String comparison. It never turns out to be 开发者_JAVA技巧0. Below I am trying to get a setting in a cookie and compare it with a given key, and return the value of that cookie. The cookies looks like this console=1|userId=5. The value is always -180 or something. I echo them out and the are the same, and the lengths are the same. Could it be an encoding issue?
$parameters = explode('|', $_COOKIE[Cisco_Rewards::REWARDS_SETTINGS_COOKIE_NAME]);
for ($i = 0; $i < count($parameters); $i++) {
$parameter = explode('=', $parameters[$i]);
if(count($parameter) > 1) {
echo strcasecmp(strtolower(trim($parameter[0])), trim(strtolower($name)));
if(strcasecmp(strtolower(trim($parameter[0])), trim(strtolower($name))) == 0) {
return $parameter[1];
}
}
}
You're missing break; in for loop!
Yes, it could be encoding issue because function strcasecmp() works with Unicode only. Multi-byte characters such as UTF-8 or UTF-16 cannot be compared with strcasecmp().
Also, strcasecmp() is case-insensitive function so using strtolower() against its parameters doesn't change function's result (string "example" is same as "EXAMPLE"m "eXaMPlE", "ExamPlE", etc).
You should set default result value (like $res=false;
) to be sure that result is set after loop.
You should replace for loop block with foreach loop like this one bellow
$parameters = explode('|', $_COOKIE[Cisco_Rewards::REWARDS_SETTINGS_COOKIE_NAME]);
// this will handle result
$res = false;
foreach ($parameters as $value) {
$param = explode('=', $value);
if(count($parameter) > 1) {
// I guess this line is just for testing result
echo "param1=".trim($param[0])."; param2=".trim($name)."; Result=".strcasecmp(trim($param[0]), trim($name)) . "<br />\n";
if(strcasecmp(trim($param[0]), trim($name))) {
$res=$param[1];
// you should break here
break;
}
}
}
// try to output result before (testing purpose only)
var_dump($res);
return $res;
But to make this solution easy you can use this function
function getParamValue($parameters, $key) {
$res = false;
$plist = explode('|', $parameters);
foreach ($plist as $pair) {
$element = explode('=', $pair);
if (trim($element[0]) == trim($key)) {
$res = trim($element[1]);
break;
}
}
return $res;
}
So if you have $parameters
string like "console=1|userid=8159"
and want to find value for $key
string "userid"
, put it into this function and it will return your result or false if $key
was not found in $parameters
list.
Example
$parameters = "console=1|userid=8159";
$name = "userid";
echo getParamValue($parameters, $name);
Output
8159
Now you can write your code this way
$parameters = explode('|', $_COOKIE[Cisco_Rewards::REWARDS_SETTINGS_COOKIE_NAME]);
$value = getParamValue($parameters, $name);
And $value takes your result or returns false if $name is not in $parameters list.
精彩评论