If语句总是false,即使值比较必须产生真结果


if statement always false even if the value comparing must produce true result

嗨,我正在测试我的程序从一个txt文件中读取字符串行。

我将把结果转移到一个数组,但是在测试if语句通过if和switch语句将最后一个数组转换为字符串时,它总是返回false/else/default结果。

我的代码是:
<?php
    $test = file('test.txt');
    foreach ($test as $row)
    {
        $temp = explode(' ', $row);
        echo "$row<br>";
        $id = (int)$temp[0];
        $date = substr($temp[1], 0, 2) . "-" . substr($temp[1], 2, 2) . "-" . substr($temp[1], 4, 4);
        $time = substr($temp[2], 0,2) .":". substr($temp[2], 2,2) .":00";
        $twt = (string)substr($row, 18);
        echo substr($row, 18);
        switch ($twt) {
            case 'I':
                echo "wew";
                break;
            default:
                echo "wow";
                break;
        }
        echo  "id: $id date: $date time: $time status: <br>";
    }
?>

它的输出是:

005 09012015 0811 I 
I wew id: 5 date: 09-01-2015 time: 08:11:00 status: 
005 09012015 1813 O 
O wew id: 5 date: 09-01-2015 time: 18:13:00 status: 
005 09022015 0756 I 
I wew id: 5 date: 09-02-2015 time: 07:56:00 status: 
005 09022015 1951 O 
O wew id: 5 date: 09-02-2015 time: 19:51:00 status: 

谢谢你的帮助。我有点困惑。我知道$temp[3]数组包含'I'值。但是它仍然在另一个输出中运行

file()默认保留换行/换行字符。所以不是I,即chr(73),而是三个字符,可能是chr(73)chr(13)chr(10)或chr(73)chr(10)chr(13)。
但是你可以传递一个标志作为第二个参数来删除这些字符(也可以忽略其他空行)。

$test = file('test.txt',  FILE_IGNORE_NEW_LINES|FILE_SKIP_EMPTY_LINES );

可能包含空格或换行符。试试这个

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

$string = str_replace(' ', '', $twt);