将文件加载到数组中并使用in_array进行检查

问题描述:

I want to check if a value exists in an array made from a text file. This is what I've got so far:

<?php
$array = file($_SERVER['DOCUMENT_ROOT'].'/textfile.txt');
if(in_array('value',$array)){
   echo 'value exists';
}
?>

I've experimented a little with foreach-loops as well, but couldn't find a way to do what I want.. The values in the text document are separated by new lines.

我想检查一个由文本文件构成的数组中是否存在值。 这就是我到目前为止: p>

 &lt;?php 
 $ array = file($ _ SERVER ['DOCUMENT_ROOT']。'/ textfile.txt')  ; 
if(in_array('value',$ array)){
 echo'value exists'; 
} 
?&gt; 
  code>  pre> 
 
 

我' 我也尝试了一些foreach循环,但找不到办法做我想要的东西..文本文档中的值用新行分隔。 p> div>

This happens because the lines of the file that become array values have a trailing newline. You need to use the FILE_IGNORE_NEW_LINES option of file to get your code working as:

$array = file($_SERVER['DOCUMENT_ROOT'].'/textfile.txt',FILE_IGNORE_NEW_LINES);

EDIT:

You can use var_dump($array) and see that the lines have a newline at the end.

It should work like this. However, the file()method doesn't strip the newline characters from the file.

$array = file($_SERVER['DOCUMENT_ROOT'].'/textfile.txt', FILE_IGNORE_NEWLINES);

Should do the trick. Check the manual for file().

$filename   = $_SERVER['DOCUMENT_ROOT'].'/textfile.txt';
$handle     = fopen($filename, 'r');
$data       = fread($handle, filesize($filename));
$rowsArr    = explode('
', $data);
foreach ($rowsArr as $row) {
    if ($row == 'value') {
        echo 'value exists';
    }
}

Do you need to use an array? You could just use string comparison.

<?php
$string = file_get_contents('textfile.txt');
if(strpos($string, 'value')){
    echo 'value exists';
}else{
    echo 'value doesn\'t exist';
}
?>