Answer the question
In order to leave comments, you need to log in
How to write values from a text file to an array in PHP?
Below is a piece of code that searches the $search array for a specific value, in my case “google.com” , and then displays a condition on the screen.
<?php
$search = array("yandex.ru", "google.com");
if (in_array("google.com", $search)) {
echo "есть";
}
else {
echo "нету";
}
?>
yandex.ru
google.com
bing.com
rambler.ru
yahoo.com
<?php
$data = file_get_contents("base.txt");
$search = explode("\r\n", $data);
if (in_array("google.com", $search)) {
echo "есть";
}
else {
echo "нету";
}
?>
Answer the question
In order to leave comments, you need to log in
Well, or just $result = file("base.txt");
It already collects lines in an array. php.net/manual/en/function.file.php
If the file is very large, then it makes sense not to create an array, but simply run through the lines in a loop without clogging the RAM ...
as an option
$base = file("base.txt");
$result = array();
foreach($base AS $row) {
$result[] = $row;
}
<?php
$array = file($filename, FILE_IGNORE_NEW_LINES);
$content = file_get_contents('base.txt');
$base = explode('\r',$content);
print_r($base);
Depending on how the file was created, you may need to write explode('\r\n',$content);
Maybe using regular expressions will be faster?:
$content = file_get_contents('base.txt');
$search = '/^<what are we looking for>$/'; // ^start, $end of string when searching using regular expressions.
$fp = fopen('base.txt');
if( preg_match($pattern, $content) )
{
if any;
}
else
{
and if there are no matches;
}
1) If the match is exact, then it's better to use file().
2) If you need to work with templates, ie. some parts of the string are not known to us, then file_get_contents and PCRE are better
A possible option, but I have no way to compare the speed now.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question