PHP
Check if Any Array Value Contains a Specific Substring
Discover how to efficiently determine if any string value within a PHP array contains a particular substring, useful for quick data validation, filtering, and search functionalities.
<?php
/**
* Checks if any string value in an array contains a specific substring.
*
* @param array $array The array to search within.
* @param string $substring The substring to search for.
* @param bool $caseSensitive Whether the search should be case-sensitive (default: false).
* @return bool True if at least one value contains the substring, false otherwise.
*/
function arrayContainsSubstring(array $array, string $substring, bool $caseSensitive = false): bool
{
foreach ($array as $value) {
// Ensure value is a string before searching
if (is_string($value)) {
if ($caseSensitive) {
if (str_contains($value, $substring)) { // PHP 8+
return true;
}
} else {
if (str_contains(strtolower($value), strtolower($substring))) { // PHP 8+
return true;
}
}
/* For PHP 7.x compatibility, use strpos:
if ($caseSensitive) {
if (strpos($value, $substring) !== false) {
return true;
}
} else {
if (strpos(strtolower($value), strtolower($substring)) !== false) {
return true;
}
}
*/
}
}
return false;
}
$keywords = ['php', 'JavaScript', 'Python', 'HTML', 'CSS'];
// Case-insensitive search
$hasScript = arrayContainsSubstring($keywords, 'script');
echo "Does 'keywords' contain 'script' (case-insensitive)? " . ($hasScript ? 'Yes' : 'No') . "
"; // Yes
$hasPhp = arrayContainsSubstring($keywords, 'PHP', true);
echo "Does 'keywords' contain 'PHP' (case-sensitive)? " . ($hasPhp ? 'Yes' : 'No') . "
"; // Yes
$hasRuby = arrayContainsSubstring($keywords, 'Ruby');
echo "Does 'keywords' contain 'Ruby'? " . ($hasRuby ? 'Yes' : 'No') . "
"; // No
$mixedArray = ['apple', 123, 'banana', ['nested'], 'orange pie'];
$hasOrange = arrayContainsSubstring($mixedArray, 'orange');
echo "Does 'mixedArray' contain 'orange'? " . ($hasOrange ? 'Yes' : 'No') . "
"; // Yes
How it works: The `arrayContainsSubstring` function iterates through each value in the provided array. It checks if the value is a string, and then uses `str_contains` (or `strpos` for older PHP versions) to determine if the specified substring exists within that value. The function supports both case-sensitive and case-insensitive searches, allowing for flexible matching. It returns `true` as soon as a match is found, improving efficiency by avoiding unnecessary iterations.