1

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";
        }
    }
3
  • 1
    You overwrite $output variable every time. What do you expect? Commented Mar 2, 2016 at 20:22
  • 2
    For only 1 match: $output = $line; break; Commented Mar 2, 2016 at 20:29
  • Thank you AbraCadaver - this actually worked for me. Commented Mar 2, 2016 at 20:38

2 Answers 2

1

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;
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

could I also use in_array? if (in_array($value, $lines))
Only if the line and the value are identical. Meaning test will not match test line etc...
1

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);
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.