I am attempting to remove certain elements of an array that contain a string. Here is my code:

foreach ($first as $temp) {
if (preg_match("/logo/", "$temp") > "0") {
unset($first[$temp]);
}
}

The array is called first and it contains the following:

27_01.jpg
27_02.jpg
27_03.jpg
29_01.jpg
29_02.jpg
29_logo.jpg << This needs to be removed
31_01.jpg
31_02.jpg
31_03.jpg

Any help would be great, TX!!!

    Sorry, I'll add here that my code doesn't work.

      Well, if 29_logo.jpg is the value you're trying to delete, unsetting $first['29_logo.jpg'] isn't going to help: you want to use the key there, not the value!

      foreach($first as $key=>$temp){
      if(preg_match('/logo/',$temp)>0){
      unset($first[$key]);
      }

      Or, faster:

      foreach($first as $key=>$temp){
      if(strpos($temp,'logo')!==false)
      unset($first[$key]);
      }

        Is it not clearer to just do this instead of testing for !== false. All you are doing is testing to see if strpos is non false and it is going to either be false or have a string position.

        foreach($first as $key=>$temp){
        if(strpos($temp,'logo'))
        unset($first[$key]);
        }

          I wonder how do you know that the second example will work faster?

            Experience, practices, and the understanding that preg_match would have to parse the regexp as a regexp, build an appropriate regexp-matching automaton, and run it. Even if there's an optimiser in there that spots literal string matches and hands such jobs off to a plain string matcher (and I'm pretty certain the PCRE library does) there's still the overhead required to actually make that determination.

            The former just uses a plain string matcher from the start.

              That won't work if "logo" appears at the start of the string; in that situation strpos($temp,'logo') would equal 0, and the condition would evaluate as false (even though 'logo' does appear in the string).

              To make sure that doesn't happen, you have to check the type of the result as well, which is what === and !== do.

              Maybe 'logo' never appears at the start of the string; but leaving in the !==false ensures that the the replacement is equivalent to the original (working) code.

              But the main reason to use strpos instead of preg_match here is because the former does the required job much faster.

                Write a Reply...