I am trying to build a function that I can use to to check a string for multiple values, kind of a generic find needle in haystack kind of function. I have split the values up into an array and tried to loop through the array and check the value against the string with a for each loop but am not experiencing the expected outcome. Please see below the function, some examples and expected outcome.
Function
function find($haystack, $needle) {
$needle = strtolower($needle);
$needles = array_map('trim', explode(",", $needle));
foreach ($needles as $needle) {
if (strpos($haystack, $needle) !== false) {
return true;
}
}
return false;
}
Example 1
$type = 'dynamic'; // on a dynamic page, could be static, general, section, home on other pages depending on page and section
if (find($type, 'static, dynamic')) {
// do something
} else {
// do something
}
Outcome
This should catch the condition whether the $type contains static or dynamic and run the same code depending on page.
Example 2
$section = 'products labels'; // could contain various strings generated by site depending on page and section
if (find($section, 'products')) {
// do something
} elseif (find($section, 'news')) {
// do something
} else {
// do something
}
Outcome
This should catch the condition specifically if the $section contains 'products' on page within the products section 'news' on a page within the news section.
--
Doesn't seem reliable on returning the desired results and can't figure out why! Any help greatly appreciated!
strtolower
call ends up not doing anything due to a typo on the next line, but this code should still work as given -- at least for these two particular cases. – Jon Apr 7 '13 at 20:52