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

Asked

Viewed 343 times

3

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().

I mean, I need to check if any string of the list 2 is contained in any URL list 1. Thanks 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";
    }
}	
?>

1 answer

2


Navigate the 2 arrays in search of 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 2 cases I transformed the link array into a large comma-separated string just to search for a filter occurrence:

So she will return 1 if she finds and 0 if she does not find:

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

So it will return to the position in which the occurrence is, if there is occurrence:

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

I hope I’ve helped!

  • PERFECT!!! Thanks Thomas Lima, very grateful for the help.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.