2016-03-02 109 views
1

我試圖驗證文本文件中是否存在php變量值,然後回顯該值。使用下面的代碼,如果變量中的值等於文本文件中的最後一個值,我的if語句纔是真的。如果變量中的值等於第一,第二,第三等值,則if語句爲false。將PHP變量與文本文件中的值進行比較

這裏是我的代碼:

$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"; 
     } 
    } 
+1

您每次都會覆蓋'$ output'變量。你能指望什麼? –

+2

只有1個匹配:'$ output = $ line;打破;' – AbraCadaver

+0

謝謝AbraCadaver - 這實際上爲我工作。 – brandozz

回答

1

對方回答糾正你的代碼,然而,用更少的代碼匹配1個或多個:

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

要使用現有方法只有1匹配,那麼break圈外的和/或定義「Sorry ...」輸出之前:

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

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

我也可以使用in_array嗎? if(in_array($ value,$ lines)) – brandozz

+0

只有在行和值相同的情況下。含義'測試'不符合'測試線'等... – AbraCadaver

1

正如評論所說,您覆蓋變量與任一條線數據或錯誤消息的每一個循環。

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); 
    } 
相關問題