简体   繁体   English

php中的字符串比较,如果条件不正常

[英]string comparison in php if condition is not working properly

I want to compare to a string but it is not working. 我想比较一个字符串,但它不起作用。

First I took it in my script and stored in a variable, and after that I stored the variable in the session. 首先我把它放在我的脚本中并存储在一个变量中,之后我将变量存储在会话中。

This is my code... 这是我的代码......

<?php
    $currencyName1 = "<script>document.write(data);</script>";

    $_SESSION["currencyVal"] = $currencyName1;

    $price = strip_tags($this->session->userdata('currencyVal'));
    $price1 = substr($price,14,17);

    if (strcmp($price,"SAR")) {
        echo "SAR"; 
    } else {
        echo "USD"; 
    }
?>

使用cookie来获取正确的字符串在$ _SESSION中,您可以使用脚本标记获取值<script>document.write(data);</script>

Agreed with @lehmanad1, You need to perform comparison like strcmp($price1,"SAR"), and keep in mind that strcmp return result as follows. 同意@ lehmanad1,你需要像strcmp($ price1,“SAR”)那样进行比较,并记住strcmp返回结果如下。

strcmp returns:
0 - if the two strings are equal
<0 - if string1 is less than string2
>0 - if string1 is greater than string2

so that in your case the if condition return 0 if strcmp($price1,"SAR")gets true, and thus else condition will be executed. 因此,在您的情况下,如果strcmp($ price1,“SAR”)变为true,则if条件返回0,因此将执行其他条件。

you need to try following approach. 你需要尝试以下方法。

if (strcmp($price1,"SAR")==0) {
    echo "SAR"; 
} else {
    echo "USD"; 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM