Penny
Penny

Reputation: 816

With array_filter and foreach , error

I have a 2 arrays as

 $check_string = array("www.salmat.", "www.webcentral.", "abpages.");

and

$files = array("http_www.salmat.com.au_.png", "http_www.webcentral.com.au_.png");

And now i want to check if value of each element in array $check_string matches with atleast part of a string of each element of array $files and if it does not match then i will echo respective values $check_string.

So i am doing with array_filter function

foreach ($check_string as $final_check) 
{
    function my_search($haystack) 
    {
        global $final_check;
        $needle = $final_check;
        return(strpos($haystack, $needle));
    }
    $matches[] = array_filter($files, 'my_search');
    if(empty($matches))
    {
       echo $final_check;
       echo "</br>";
    }
}

But with this code i get an error

Fatal error:  Cannot redeclare my_search() (previously declared in same file)

Can any one suggest any solution

i refereed this and this but cannot get through the solution Thankyou

Upvotes: 1

Views: 858

Answers (1)

Hanky Panky
Hanky Panky

Reputation: 46900

 function my_search($haystack) 
    {
        global $final_check;
        $needle = $final_check;
        return(strpos($haystack, $needle));
    }

That function needs to be defined outside the loop. And you can just call it again and again in the loop. Currently you are trying to redeclare it on every iteration of the loop.

Not going to suggest further fixes to your code since it's logic is not very good. You can try something like this

$check_string = array("www.salmat.", "www.webcentral.", "abpages.");
$files = array("http_www.salmat.com.au_.png", "http_www.webcentral.com.au_.png");

foreach($check_string as $check)
{
  $found=FALSE;
  foreach($files as $file)
  {
    if(stristr($file,$check)!==FALSE)
      $found=TRUE;
  }
  if(!$found)
    echo $check,"\n";
}

Fiddle

Of course you can improve it and use less code but that gives you a direction.

Upvotes: 3

Related Questions