在PHP中将数组与字符串进行比较时,如果条件为false

时间:2018-10-23 01:24:59

标签: 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>"; 

    }

} 

enter image description here

enter image description here

1 个答案:

答案 0 :(得分:1)

欢迎叠加Billy。您可以尝试以下两种解决方案:使用trim()strpos()函数。

使用trim()将删除字符串中的任何前导或尾随空格:

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

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

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