I've got a piece of code searching a text file for an email address, returning the two numbers on the same line. The file looks like:
24/08/2017,[email protected],1,2
21/05/2018,[email protected],1,2
21/05/2018,[email protected],2,2
My code currently looks like
$lines = file("log.txt");
$found = 0;
foreach ($lines as $line){
if (strpos($line, $email) !==false){
$found = true;
$arrayOfLine = explode(",", $line);
$foundGroup = $arrayOfLine[2];
$foundVideo = $arrayOfLine[3];
}
elseif (strpos($line, $email) ===false){
$found = false;
}
}
When I run this code, through a HTML form that takes in the email address to be searched for, it only finds matching emails if they were the last entered - in my example above, [email protected] wouldn't return a match, but [email protected] would. What am I missing that's preventing it from turning up matches?
You are not terminating your loop when you find an answer, meaning it continues to run even if it found a match and overwrites any previous match. Add a break;
after you assigned $foundGroup
and $foundVideo
.
You also have two evaluations checking the same thing. Set the $found
flag to false
at the start of the loop. If your loop fails to find a match, it'll still be false. You don't need to compare twice.
$found = false;
foreach ($lines as $line){
if (strpos($line, $email) !==false){
$found = true;
$arrayOfLine = explode(",", $line);
$foundGroup = $arrayOfLine[2];
$foundVideo = $arrayOfLine[3];
break; // stop searching for more matches
}
}