我想創建一個函數,檢查輸入的單詞是否已經在我的數據庫中。in_array方法只運行一次?
我使用以下代碼:
public function contains($string, $pieces)
{
$this->getWords();
$arr = $this->_data; // Get everything from DB
$words = array();
$foundWords = array();
foreach($arr as $key)
{
$words[] = $key->word; // Put words in array
}
foreach($words as $item)
{
if (in_array($item, $words))
{ // Check if entered words are in the DB array
$foundWords[] = $item; // Put already existing words in array
print_r($foundWords);
echo "Match found: ";
echo $item . '<br>'; // Echo found words
return true;
}
echo "Not found!";
return false;
}
}
的問題是,它只檢查從輸入的單詞排列的第一個字。 有誰知道爲什麼會發生這種情況?
實施例:
用戶輸入'This is a test'
。 的DB包含下列的話:This, is, a, test
代碼的輸出現在應該Match found: This, is, a, test
,並且$foundWords
數組應該包含這些詞。
取而代之的是,它只找到第一個單詞,$foundWords
數組只包含第一個單詞。所以,Match found: This
。
你知道什麼'return'確實在函數/方法,不是嗎? –
您需要在此處使用'break'語句並在函數的最後一行返回您的值。 –
@MarkBaker感謝您通知我。我完全忘了它停止了這個功能。這解決了它! – Chris