How can I search for exact number through a file containing thousands of numbers?
If we say that we have a text f开发者_高级运维ile containing order numbers or references (1 Number per 1 Line only) what is the best way to find/validate an input (number entered in form for example) against those numbers in a file?
Is there a simple idea to do it? Assume we have thousands of numbers to search through.
Thank you very much.
If memory is not an issue (Demo):
if (in_array($number, file('numbers.txt', FILE_IGNORE_NEW_LINES))) {
// number exists - do something
}
Since file
returns an array where each line is one element in the array, you can also use array_search
to find the line where it was found or array_keys
to find all the lines where it was found.
If memory is an issue (Demo):
foreach(new SplFileObject('numbers.txt') as $line) {
if ($number == $line) {
// number exists - do something
break;
}
}
When in doubt which to use, benchmark.
Marking CW because there is already several questions asking how to read a file line by line or efficiently.
$file = file_get_contents("filename.txt");
if (strpos($file, "search string") === false) {
echo "String not found!";
}
if the numbers are ordered: don't load the whole file into memory. seek to the middle of the file and read the number. if your number is < than the middle, seek the middle of the first half. otherwise seek the middle of the second half...
Binary Search
If you want to return the line number of the location of the matching number in the file, you can use file() to return the reference file as an array of file lines.
$search_string = '42';
$file_name = 'test_file.txt';
$file = file($file_name);
foreach($file as $line_number=>$number){
if(intval($search_string) == $number){
$found_on_lines[] = $line_number;
}
}
echo "String ".$search_string;
if(count($found_on_lines)>0){
echo " found on line(s):</br> ";
foreach($found_on_lines as $line){
echo $line."</br>";
}
}
else{
echo "not found in file ".$file_name.".";
}
This will output
String 42 found on line(s):
9
256
if your reference file contains the number '42' on lines 9 and 256.
精彩评论