Check if an element of an array is contained in every element of another array with php

Question:

I have two arrays, I need to take each element of the second array and check if it is contained in any element of the first array using, for example, the strpos() function.

In other words, I need to check if any string from list 2 is contained in any URL from list 1. Thank you in advance.

<?php
$ads = array();
$ads[0] = "https://superman.com.br";
$ads[1] = "https://photoshop.com.br?galid=";
$ads[2] = "https://mercado.com.br";
$ads[3] = "https://xdemais.com.br";
$ads[4] = "https://imagens.com.br";
$ads[5] = "https://terceiraidade.com.br";
$ads[6] = "https://goldenartesgraficas.com.br";
$ads[7] = "https://empregos.com.br";
$ads[8] = "https://umcentavo.com.br";
$ads[9] = "https://classificados.com.br";


	$filter_ads = array();
	$filter_ads[0] = "galid=";
	$filter_ads[1] = "gslid=";
	$filter_ads[2] = "ghlid=";
	$filter_ads[3] = "gplid=";
	$filter_ads[4] = "gulid=";
	$filter_ads[5] = "gllid=";
	$filter_ads[6] = "gklid=";
	$filter_ads[7] = "grlid=";
	$filter_ads[8] = "gwlid=";
	$filter_ads[9] = "gelid=";	

foreach($ads as $ads_x) {
    if (strpos($ads_x, in_array($filter_ads, $ads))) {
    	echo "Existe";
    }
}	
?>

Answer:

Scroll through the 2 arrays looking for an occurrence:

foreach ($ads as $link) {

    foreach ($filter_ads as $ads) {

        if (strpos($link, $ads)){
            echo "Achei aqui: <br />"
            . "Link: ". $link ." <br />"
            . "parametro: ". $ads ."<br /><br />";
        }

    }

}

You can still test these other 2 options, depending on your need they can solve. In both cases I transformed the array of links into a large comma-separated string just to look for an occurrence of the filter:

So it will return 1 if found and 0 if not found:

foreach ($filter_ads as $filter) {
    echo preg_match("/". $filter ."/", implode(",", $ads));
}

So it will return the position where the occurrence is, if there is an occurrence:

foreach ($filter_ads as $filter) {
    echo strpos(implode(",", $ads), $filter);
}

Hope this helps!

Scroll to Top