Check if String Contains Words from an Array in PHP

This tutorial will discuss about a unique way to check if string contains words from an array in php.

Suppose we have a array that contains certain words/strings. A part from that, we have also a main string i.e.

$strValue = "Last Coder";
$wordsArr = ["Coder", "Manager", "Last", "Main"];

Now we want to check if these string $strValue contains any word/string from the array $wordsArr.

We have created a separate function for this,

function containsWords($str, $wordsArr)
{
    $result = false;
    // Iterate over all words/strings in array
    foreach ($wordsArr as $word) {
        // For each word, check if it exists in the string
        if (strpos($str, $word) !== false) {
            // If string contains this word, then break the loop
            // and return true
            $result = true;
            break;
        }
    }
    return $result;
}

It accepts a string and an array as arguments, and it returns true if the string contains any word from the array.

Inside this function we will iterate over all the words in the array and for each word we will check if it exists in the given string using the strpos() function. If any word exists in the given string, then that means the string contains at least a value from an array in PHP.

Let’s see the complete example,

<?php
/**
 * Checks if a string contains any of the words
 * from an array using strpos() and a foreach loop.
 *
 * @param string $str The string to check.
 * @param array $wordsArr The array of words to check for in the string.
 * @return bool True if the string contains any of the words, false otherwise.
 */
function containsWords($str, $wordsArr)
{
    $result = false;
    // Iterate over all words/strings in array
    foreach ($wordsArr as $word) {
        // For each word, check if it exists in the string
        if (strpos($str, $word) !== false) {
            // If string contains this word, then break the loop
            // and return true
            $result = true;
            break;
        }
    }
    return $result;
}


$strValue = "Last Coder";
$wordsArr = ["Coder", "Manager", "Last", "Main"];

if (containsWords($strValue, $wordsArr)) {
    echo "The string contains one or more words from the array.";
} else {
    echo "The string does not contain any words from the array.";
}
?>

Output

The string contains one or more words from the array.

Summary

We Learned how to check if a string contains Words from an Array in PHP.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top