Search code examples
phpif-statementforeachbooleanstrpos

How to return a boolean if a string contains one of an array of substrings?


I'm struggling with a simple function that loops through an array and returns true only if it finds a given substring in one of the array's elements.

For some reason, I'm ALWAYS getting false... even when the $email parameter is contains one of the valid domains. Ex: scoobydoo@domain1.com.

function check_email($email) {
    $whitelist_domains = array(
        '@domain1.com',
        '@domain2.com',
        '@domain3.com'
    );
    $output = FALSE;
    foreach ($whitelist_domains as $domain) {   
        $pos = strpos( $email, $domain ); 
        if ( $pos ) {
            $output = TRUE;
        }
    }
    return $output;
}

Solution

  • you are not breaking the loop if you find the domain, so what you are getting is actually the result for the LAST string checked only. just add break; after $output = TRUE;