Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load file into array and check it with in_array

Tags:

file

php

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.

like image 690
Nisto Avatar asked Nov 25 '25 16:11

Nisto


1 Answers

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.

like image 156
codaddict Avatar answered Nov 27 '25 06:11

codaddict



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!