We have a function in PHP, in_array, which checks if the given value is present in an array. I guess I wanna do a reverse of it. I have a set of strings:
$words = array("hello", "world");
And, I wanna check, if a given string has these words, by giving parameters whether all or any.
$string = "Hello, World!";
$second = "Hello and Welcome!";
in_string($words, $string, "all");
in_string($words, $string, "any");
What I have right now is, using stripos(). I do not wanna use regex.
Current Code:
<?php
/**
* Checks if the given words is found in a string or not.
*
* @param Array $words The array of words to be given.
* @param String $string The string to be checked on.
* @param String $option all - should have all the words in the array. any - should have any of the words in the array
* @return boolean True, if found, False if not found, depending on the $option
*/
function in_string ($words, $string, $option)
{
if ($option == "all")
foreach ($words as $value)
$isFound = $isFound && (stripos($string, $value) || false);
else
foreach ($words as $value)
$isFound = $isFound || (stripos($string, $value) || false);
return $isFound;
}
?>
My question is, can this be improved? Any thoughts?
Update #1: Current Code Updated:
/**
* Checks if the given words is found in a string or not.
*
* @param Array $words The array of words to be given.
* @param String $string The string to be checked on.
* @param String $option all - should have all the words in the array. any - should have any of the words in the array
* @return boolean True, if found, False if not found, depending on the $option
*/
function in_string ($words, $string, $option)
{
if ($option == "all")
{
$isFound = true;
foreach ($words as $value)
$isFound = $isFound && (stripos($string, $value) !== false);
return $isFound;
}
else
{
$isFound = true;
foreach ($words as $value)
if (stripos($string, $value) !== false) return true;
return $isFound;
}
}
Now the function is working as expected. But I need a better performance in the foreach() part and all. Anything possible for improvements?
Update #2: Improvements Added
<?php
/**
* Checks if the given words is found in a string or not.
*
* @param Array $words The array of words to be given.
* @param String $string The string to be checked on.
* @param String $option all - should have all the words in the array. any - should have any of the words in the array
* @return boolean True, if found, False if not found, depending on the $option
*/
function in_string ($words, $string, $option)
{
if ($option == "all")
{
foreach ($words as $value)
if (stripos($string, $value) === false)
return false;
return true;
}
else
{
foreach ($words as $value)
if (stripos($string, $value) !== false)
return true;
return false;
}
}
?>
Just the same code as the person below me, with the break; added. I don’t have enough rep to comment apparently