Load file into array and check it with 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.
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('\n', $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';
}
?>
精彩评论