Search code examples
phparraysstrpos

Using an array as needles in strpos


How do you use the strpos for an array of needles when searching a string? For example:

$find_letters = array('a', 'c', 'd');
$string = 'abcdefg';

if(strpos($string, $find_letters) !== false)
{
    echo 'All the letters are found in the string!';
}

Because when using this, it wouldn't work, it would be good if there was something like this


Solution

  • @Dave an updated snippet from http://www.php.net/manual/en/function.strpos.php#107351

    function strposa($haystack, $needles=array(), $offset=0) {
            $chr = array();
            foreach($needles as $needle) {
                    $res = strpos($haystack, $needle, $offset);
                    if ($res !== false) $chr[$needle] = $res;
            }
            if(empty($chr)) return false;
            return min($chr);
    }
    

    How to use:

    $string = 'Whis string contains word "cheese" and "tea".';
    $array  = array('burger', 'melon', 'cheese', 'milk');
    
    if (strposa($string, $array, 1)) {
        echo 'true';
    } else {
        echo 'false';
    }
    

    will return true, because of array "cheese".

    Update: Improved code with stop when the first of the needles is found:

    function strposa(string $haystack, array $needles, int $offset = 0): bool 
    {
        foreach($needles as $needle) {
            if(strpos($haystack, $needle, $offset) !== false) {
                return true; // stop on first true result
            }
        }
    
        return false;
    }
    $string = 'This string contains word "cheese" and "tea".';
    $array  = ['burger', 'melon', 'cheese', 'milk'];
    var_dump(strposa($string, $array)); // will return true, since "cheese" has been found