cakephp 在PHP中比较两个相同的字符串返回false

5q4ezhmt  于 2022-11-11  发布在  PHP
关注(0)|答案(5)|浏览(169)

我试图比较两个字符串。当我回显它们时,它们看起来是相同的,但是当我用'=='操作符比较它们时,它返回false。例如,当在我的数据库上运行下面的代码时,它输出类似“APPARENTLY Apple does not equal Apple”的内容。原因是什么?

if ($this->data['list_text']) { // The user has entered into textarea

    $list = nl2br($this->data['list_text']);

    $list_array = explode('<br />', $list);

    $ranking = 1;
    $company_array = $this->CompanyList->CompanyRanking->Company->find('list', null);

    // This is the comparison bit
    foreach ($list_array as $key => $value) {
        $companyId = null;
        foreach ($company_array as $key2 => $value2) {
            if ($value2 != $value) {
                echo 'APPARENTLY ' . $value2 . ' does not equal ' . $value;
            } else {
                $companyId = $key2;
                break;
            }
        }

        $this->data['CompanyRanking'][$ranking]['ranking'] = $ranking;
        $this->data['CompanyRanking'][$ranking]['company_id'] = $companyId;
        $ranking++;
    }
}
qni6mghb

qni6mghb1#

尝试var_dump()而不是echo。

echo 'APPARENTLY '.$value2.' does not equal '.$value;   
echo '<pre>Debug: ';
echo 'value='; var_dump($value);
echo 'value2='; var_dump($value2);
echo '</pre>';

它提供附加信息。例如,实际类型和字符串的长度。

bttbmeg0

bttbmeg02#

字符串中是否有您看不到的多余空格?请尝试修剪它们。

dgjrabp2

dgjrabp23#

请尝试检查所比较的两个字符串的编码。
也许它是UTF-8ISO 8859-1相比,有一些奇怪的字符。

jw5wzhpr

jw5wzhpr4#

我同意Olafur的观点。我删除了trim并用preg_replace替换它,因为你假设$value和$value2是公司ID。如果公司ID应该是字母数字,包含连字符等,你可以对这些进行快速修改a..这个版本应该做到这一点:

if ($this->data['list_text']) { 
    $list = nl2br($this->data['list_text']);
    $list_array = explode('<br />', $list);

    $ranking = 1;
    $company_array = $this->CompanyList->CompanyRanking->Company->find('list',null);

    foreach ($list_array as $key => $value) {

        // remove any non digit characters
        $value = preg_replace('/[^0-9]/i','', $value); 
        $companyId = null;

        foreach ($company_array as $key2 => $value2) {

            // remove any non digit characters
            $value2 = preg_replace('/[^0-9]/i','', $value2); 

            if ($value2 != $value) {
                echo 'values not equal';                
            } else {
                $companyId = $key2;
                break;
            }
        }

        $this->data['CompanyRanking'][$ranking]['ranking'] = $ranking;
        $this->data['CompanyRanking'][$ranking]['company_id'] = $companyId;
        $ranking++;
    }
}
h79rfbju

h79rfbju5#

尝试使用trim()来表示任何白色,并使用var_dump()来查看是否有其他内容与它一起传递。

相关问题