3

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.

4 Answers 4

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Oh, that explains a lot! Thanks!
0

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

Comments

0
$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';
    }
}

Comments

0

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';
}
?>

2 Comments

Yeah, sort of. I want "accurate values", so an array would probably be best.
Then codaddict's answer fits you best. ;D

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.