Chris Chris - 7 months ago 9
PHP Question

The in_array method only ran once?

I'm trying to create a function that checks if the entered words are already in my DB.

I'm using the following code:

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


The problem is, it only checks the first word from the entered words array.
Does anyone know why this might be happening?

Example:

User enters
'This is a test'
.
The DB contains the following words:
This, is, a, test


The output of the code should now be
Match found: This, is, a, test
, and the
$foundWords
array should contain these words.

Instead, it only finds the first word and the
$foundWords
array only contains the first word. So,
Match found: This
.

Answer

Create a variable for return status from the function. Here i use $flag variable for checking the status of the word. Default i set the variable as false, and if the word found then turn the variable as true and breakfrom the loop and return the flag.

public function contains($string, $pieces){
    $flag = false;
    $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

            $flag = true; //set true and break from the loop
            break;
        }else{
            echo "Not found!";
            $flag = false;
        }               
    }
    return $flag;
}