【问题标题】:if compare doesn't work in php如果比较在 php 中不起作用
【发布时间】:2015-06-11 09:58:16
【问题描述】:

比较有问题。我在执行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']))

【问题讨论】:

  • 问题可能是因为您在文本文件的每一行末尾都有一个换行符 (\n)。所以:"xy\n" === "xy" 与您可能看到的不同。 (解决方案?只需trim() 文件中的行,例如if (trim($line) == $rowActual['pid'])

标签: php if-statement compare


【解决方案1】:

你可以试试:

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

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

    • 感谢您的提示 :)
    猜你喜欢
    • 1970-01-01
    • 2018-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-28
    相关资源
    最近更新 更多