Check if Array Contains a substring in PHP

This tutorial will discuss about unique ways to check if any string an array contains a substring in PHP.

Table Of Contents

Method 1: Using a Regex Pattern

The preg_grep() function in PHP accepts a regex string and an array as arguments, and returns a new array containing only those strings from the array which matches the given regex pattern.

Now we want to find all the strings from an array which contains a given substring. For this, we are going to pass the regex pattern "/$subStr/i" along with the array as arguments into the preg_grep() function. Here $subStr is the substring.

It will return an array containing only those string which has the given substring. If the returned array is empty, then it means that there is no string in the array which contains the given substring. Whereas if array is not empty then it means there is at least a string in the array which contains the specified substring.

Let’s see the complete example,

<?php
$arr = array('for', 'why', 'this', 'here', 'some');
$subStr = 'is';

// Get  array of entries that matches the given regex pattern
$matchedEntries = preg_grep("/$subStr/i", $arr);

// Check if array is empty
if (!empty($matchedEntries)) {
    echo "Yes, the array contains the specified substring";
} else {
    echo "No, the array does not contains the specified substring";
}
?>

Output

Yes, the array contains the specified substring

Method 2: Using foreach and strpos()

Iterate over all the elements of array using foreach(), and during iteration for each string element of array, pass it along with the substring into the strpos() function. It will return the index position of first occurrence of substring in the given string. Whereas if the given substring does not exist in the string it will return false. So using this function we can check if this string element contains a given substring or not.

As soon as we encounter a string from array which contains the given substring, we will break the loop and mark the result value as true. At the end of the loop, if the result value is true that it means that atleast a string in array contains the specified substring.

Let’s see the complete example,

<?php
$arr = array('for', 'why', 'this', 'here', 'some');
$subStr = 'is';

$result = false;
foreach ($arr as $value) {
    if (strpos($value, $subStr) !== false) {
        $result = true;
        break;
    }
}

if ($result) {
    echo "Yes, the array contains the specified substring";
} else {
    echo "No, the array does not contains the specified substring";
}
?>

Output

Yes, the array contains the specified substring

Summary

We learned about two ways to check if an array contains a specified substring 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