I have a array which has 4 values. I want to search a text file for the values inside the array and return the line number the string is available. But when my code is executed it gives only the line number of the first value in the array and prints the same line number for the rest of the array values also.
$scheme_code = array("106212","112422","114239","128053");
$search = $scheme_code[0];
$i = 0;
$line_number = false;
$count = 0;
$handle = fopen("http://portal.amfiindia.com/spages//NAV0.txt", 'r');
foreach ($scheme_code as $code) {
echo $code."<br>";
while (($line = fgets($handle, 4096)) !== FALSE and !$line_number) {
$count++;
$line_number = (strpos($line, $code) !== FALSE) ? $count : $line_number;
}
echo "The line number is".$line_number."<br>";
//fclose($handle);
}
My output is like this 106212 The line number is 5386 112422 The line number is 5386 114239 The line number is 5386 128053 The line number is 5386
5386 is the line number of the value 106212.
When i echo the $code
. It prints the $code
but the line number for the first code only gets printed for the rest of the codes.
You need to reset the value of $line_number outside the while loop. That is the condition resulting into non execution of while loop.
Thus declare the variable $line_number inside foreach.