brandozz
brandozz

Reputation: 1119

Comparing PHP variable to values in text file

I'm trying to validate that a php variable value exists in a text file then echo that value. Using the code below, my if statement is only true if the value in the variable is equal to the last value in the text file. If the value in the variable is equal to the first, second, third, etc values the if statement is false.

Here is my code:

$lines = file("file.txt");
$value = $_GET['value'];

    foreach ($lines as $line) {
        if (strpos($line, $value) !== false) {
            $output = $line;
        } else {
            $output = "Sorry, we don't recognize the value that you entered";
        }
    }

Upvotes: 1

Views: 1442

Answers (2)

AbraCadaver
AbraCadaver

Reputation: 78994

The other answer corrects your code, however to match 1 or more with less code:

$output = preg_grep('/'.preg_quote($value, '/').'/', $lines);

To use the existing approach for only 1 match then break out of the loop and/or define the "Sorry..." output before:

$output = "Sorry, we don't recognize the value that you entered";

foreach ($lines as $line) {
    if (strpos($line, $value) !== false) {
        $output = $line;
        break;
    }
}

Upvotes: 1

Xorifelse
Xorifelse

Reputation: 7911

As stated in the comment, you overwrite the variable with every loop with either line data or an error message.

   foreach ($lines as $line) {
        if (strpos($line, $value) !== false) {
            $output[] = $line;
        }
    }

    if(empty($output)){
      echo "Sorry, we don't recognize the value that you entered";
    } else {
      print_r($output);
    }

Upvotes: 1

Related Questions