Check If Array Contains Substring In PHP
If you’re working with PHP arrays, you may need to check if a specific substring exists in the array. The good news is that there are several built-in PHP functions that can help you accomplish this task. In this blog post, we’ll explore some of these functions and show you how to use them to Check If Array Contains Substring In PHP. Whether you’re a beginner or an experienced PHP developer, this post will provide you with the knowledge you need to efficiently search for substrings in PHP arrays.
Here’s an example of a function that Check If Array Contains Substring In PHP:
1 2 3 4 5 6 7 8 |
function array_contains_substring($array, $substring) { foreach ($array as $element) { if (strpos($element, $substring) !== false) { return true; } } return false; } |
This function takes two parameters: an array and a substring to search for. It loops through the array using a foreach
loop and uses the strpos()
function to check if the substring is present in each array element. If the strpos()
function returns a value that is not false
, then the function returns true
indicating that the substring is present in the array. If the function completes the loop without finding the substring, it returns false
.
You can call this function like this:
1 2 3 4 5 6 7 8 9 10 11 12 |
// Define an array $fruits = array("apple", "banana", "cherry", "kiwi"); // Define the substring to search for $search = "an"; // Call the function if (array_contains_substring($fruits, $search)) { echo "The array contains the substring $search\n"; } else { echo "The array does not contain the substring $search\n"; } |
In this example, we define an array of fruits and a substring to search for. We then call the array_contains_substring()
function passing in the array and the substring as parameters. The function returns true
if the substring is present in any of the array elements and false
otherwise. We use an if
statement to check the return value of the function and output a message accordingly.
Related Links:
- PHP manual on array functions: https://www.php.net/manual/en/ref.array.php
- Tutorial on PHP in_array() function: https://www.geeksforgeeks.org/php-in_array-function/
- Example of using array_filter() function to check if array contains substring: https://www.tutorialrepublic.com/php-tutorial/php-array-filter-function.php
- PHP documentation on preg_grep() function for pattern matching in arrays: https://www.php.net/manual/en/function.preg-grep.php
Hi, i think that i saw you visited my site so i came to “return the favor”.I am
trying to find things to enhance my site!I suppose its ok to use
some of your ideas!!
sure