Upload the file to the 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 have so far:

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

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

+3
source share
4 answers

This is because the lines of the file that become array values ​​have a terminating new line. You need to use the FILE_IGNORE_NEW_LINES file option so that your code works like:

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

EDIT:

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

+4
source

. file() .

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

. manual ().

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

? .

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

Source: https://habr.com/ru/post/1761895/


All Articles