Search code examples
phparraysstrpos

PHP - Checking whether a string exists in an entire array?


Basic array question:

$string = "The quick brown cat";

$check1 = "apple";
$check2 = "ball";
$check3 = "cat";

if ( (stripos($string, $check1) === false) ||
     (stripos($string, $check2) === false) ||
     (stripos($string, $check3) === false)
   ) {
   echo "Fail";
}

How do I condense the above using an array ($check[])?

Thanks!


Solution

  • You should still use strpos()

    $checks = array('apple', 'ball', 'cat');
    foreach($checks as $c){
      if(strpos($string, $c) === false){
        echo "Fail";
        break;
      }
    }
    

    benchmarks: strpos() wins

    <?php
    
    function benchmark($callback){
      echo sprintf('%-30s: ', $callback);
      $t = microtime(true);
      foreach(range(1, 10000) as $n){
        call_user_func($callback);
      }
      echo (microtime(true)-$t)."\n";
    }
    
    function smotchkkiss_strpos(){
      $string = "The quick brown cat";
      $checks = array('apple', 'ball', 'cat');
      foreach($checks as $c){
        if(strpos($string, $c) === false){
          break;
        }
      }
    }
    
    function konforce_preg_match(){
      $string = "The quick brown cat";
      preg_match('/apple|ball|cat/i', $string);
    }
    
    function konforce_preg_match_implode(){
      $string = "The quick brown cat";
      $checks = array('apple', 'ball', 'cat');
      preg_match('/'.implode('|', $checks).'/i', $string);
    }
    
    
    benchmark('smotchkkiss_strpos');
    benchmark('konforce_preg_match');
    benchmark('konforce_preg_match_implode');
    
    # output
    # smotchkkiss_strpos            : 0.020166158676147
    # konforce_preg_match           : 0.032760858535767
    # konforce_preg_match_implode   : 0.045573949813843
    
    ?>