Search code examples
phpstringforeachstrpos

Having trouble using strpos()


This function results in 6 matches, although it should result in 2 matches. I am not sure what I am doing wrong here.

public function displayPrize() {
        $testString = "The cow jumped over the moon";
        $userString = "The cow";

        $magicArray = (explode(" ", $testString));

        foreach ($magicArray as $value) {
            if (strpos(" ", $userString, $value) !== false) {
                $count++;
            }
        }

        echo $count . ' matches';
    }

Solution

  • if (strpos(" ", $userString, $value) !== false)
    

    must become

    if (strpos($userString, $value) !== false)