tags:

views:

35

answers:

4

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.

A: 

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().

svens
+3  A: 

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.

codaddict
Oh, that explains a lot! Thanks!
Nisto
A: 
$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';
    }
}
Alexander.Plutov
A: 

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';
}
?>
Stann0rz
Yeah, sort of. I want "accurate values", so an array would probably be best.
Nisto
Then codaddict's answer fits you best. ;D
Stann0rz
Indeed it does.
Nisto