Check if string contains all values in array with php
Solution
function str_contains_all($haystack, array $needles) {
foreach ($needles as $needle) {
if (strpos($haystack, $needle) === false) {
return false;
}
}
return true;
}
Usage:
$haystack = 'foo, bar, baz';
$needles = array('foo', 'bar', 'baz');
if (str_contains_all($haystack, $needles)) {
echo "Success\n";
// ...
}
Notes
Since you specified that you only wish to perform an action when the "haystack" string contains all the substring "needles", it is safe to return false
as soon as you discover a needle that is not in the haystack.
Other
Using if (...): /* ... */ endif;
is fairly uncommon in PHP from my experience. I think most developers would prefer the C-style if (...) { /* ... */ }
syntax.