如果比较在 php 中不起作用

if compare doesn't work in php

我对比较有疑问。我在执行 nmap 并将 pid 保存在数据库中后执行此代码:

include("classes/database.php"); //conection to database

$selectActual = "SELECT * from InfActual";
$resultActual = $conn->query($selectActual);
if ($resultActual->num_rows > 0) {
    while ($rowActual = $resultActual->fetch_assoc()) {
        echo "pid in DB: " . $rowActual['pid'] . "<br>";

        echo "................<br>";

        exec("pgrep -l 'nmap' | cut -d' ' -f1 > pids.txt");

        $fh = fopen('pids.txt', 'r');

        while ($line = fgets($fh)) {
            if ($line == $rowActual['pid']) {
                echo "pid in pids.txt: " . $line . " and pid in DB: " . $rowActual['pid'] . " are the same <br>";
            } else {
                echo "pid in pids.txt: " . $line . " and pid in DB: " . $rowActual['pid'] . " are NOT the same <br>";
            }
        }
    }
}
fclose($fh);

这是结果:

pid in DB: 5926
................
pid in pids.txt: 5926 and pid in DB: 5926 are NOT the same 

为什么它告诉我不一样?我不明白。 提前谢谢你。

[已解决]

if (intval($line) == intval($rowActual['pid']))

你能试试吗:

if (intval($line) == intval($rowActual['pid'])) {...}

读取文件时数据中可能有一些不需要的字符。

如果您只是想比较一下,Sanjay 的答案就是您所需要的。但是如果你想格式化数据,我建议使用 trim ,它会从值中去除任何字符或空格。

while...

$line = trim($line);
$rowActual['pid'] = trim($rowActual['pid']);

if ($line == $rowActual['pid']) {...}