need help looping through array most effciently

Discussion in 'PHP' started by phantom, Oct 16, 2007.

  1. #1
    If I have an array of bad words:

    $badwords = array( "bad" , "killgood" , "slaughter");


    and a variable:
    $check
    Where he variable $check can be a string like: "The bad man killed everyone good"


    What is the most efficient way to loop through the $badwords array to see if a word in $check exists in $badwords and if it does - then do (or not do) something?



    Thanks!
     
    phantom, Oct 16, 2007 IP
  2. jestep

    jestep Prominent Member

    Messages:
    3,659
    Likes Received:
    215
    Best Answers:
    19
    Trophy Points:
    330
    #2
    This is how I would do it:

    
    
    foreach($badwords as $suspect){
    
    if(strpos($check,$suspect) !== false){
    
    //the bad word is in there, do something
    
    }
    
    }
    
    PHP:
    There are a ton of ways to do it, but strpos is the quickest function if you only need to find if needle is in haystack.
     
    jestep, Oct 16, 2007 IP
  3. TlcAndres

    TlcAndres Peon

    Messages:
    11
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Well as far as I've heard this method is more efficient

    ...And I wish I knew why it isn't formatting my code correctly..
     
    TlcAndres, Oct 16, 2007 IP
  4. phantom

    phantom Well-Known Member

    Messages:
    1,509
    Likes Received:
    32
    Best Answers:
    0
    Trophy Points:
    140
    #4
    Ok Guys thanks.....now that I got that working I have another problem, matching case.......How would I match words no matter the case as in uppercase or lower case or a mixture of both?

    ....and do it as efficiently and as fast as possible?
     
    phantom, Oct 16, 2007 IP
  5. jnestor

    jnestor Peon

    Messages:
    133
    Likes Received:
    7
    Best Answers:
    0
    Trophy Points:
    0
    #5
    use stristr instead of strpos
     
    jnestor, Oct 16, 2007 IP
  6. phantom

    phantom Well-Known Member

    Messages:
    1,509
    Likes Received:
    32
    Best Answers:
    0
    Trophy Points:
    140
    #6
    Nice!


    Works like a charm guys ...thanks to all of you!
     
    phantom, Oct 16, 2007 IP