首页 > 解决方案 > 在 PHP 中将数组与字符串进行比较时,如果条件为假

问题描述

我有一个 FOR 循环和一个 IF 语句,用于检查 txt 文档中的每一行是否有某个单词。但是,当循环到达包含值“header”的行时,IF 语句不认为这是真的。

txt 文件

header
bods
#4f4f4f
30
100
1
text
this is content for the page
#efefef
10
300
2
img
file/here/image.png
300
500
filler
3
header
this is header text
#4f4f4f
30
100
4

.php 文件

$order = array();
$e = 0;
$h = 0;
$headerCount = 0;
$textCount = 0;
$imgCount = 0;

//Open file putting each line into an array
$textFile = fopen("test.txt","r+");
$inTextFile = fread($textFile, filesize("test.txt"));
$arrayFile = explode("\n", $inTextFile);
$arrayFileSize = sizeof($arrayFile);
$elementCount = $arrayFileSize / 6;

for ($x = 0; $x < $arrayFileSize; $x++) {

    if ($arrayFile[$x] == "header") {

        echo $x;
        echo " Yes : ".$arrayFile[$x] . "<br>"; 
        $headerCount++;

    }
    else {

        echo $x;
        echo " No : " . $arrayFile[$x] . "<br>"; 

    }

} 

在此处输入图像描述

在此处输入图像描述

标签: php

解决方案


欢迎来到 Stack Overflow Billy。您可以尝试两种解决方案:trim()使用strpos().

Usingtrim()将从字符串中删除任何前导或尾随空格:

if (trim($arrayFile[$x]) == "header") {...}

使用strpos()可以帮助您检查单词“header”是否存在于字符串中的任何位置。如果给定的单词不存在,它将返回false

if (strpos($arrayFile[$x], "header") !== false) {...}

推荐阅读