Hello all, i have two arrays i.e

$ar1=array("Mobile","shop","software","hardware");

and

$arr2=arry("shop","Mobile","shop","software","shop")

i want to compare the elements of arr2 to arr1 i.e

foreach($arr2 as $val)
    { 
        if(in_array($val, $arr1))
        {    
            //mycode to insert data into mysql table

            variable++;  // here there should be a variable that must be increamented when ever match found in $arr2 so that it can be saved into another table.
        }
         $query="update table set shop='$variable',Mobile='$variable'.......";
     }

my problem is when ever a match is found in if(in_array($val, $arr1) my code will be executed. here i want a variable or an array to count how many times that matched item/element is found i.e for shop=3 and for mobile and software it should be 1. Later in my update query i want to set the fields with this count

Hi zeeshan,

You could try using this method below,

$arr3 = array();
foreach($arr2 as $key => $val)
{ 
	if(in_array($val, $arr1))
	{    

		$arr3[$val] += 1; // Increments the value if its found
	}
}
echo "<pre>";
print_r($arr3);
echo "</pre>";
$mobile = $arr3[$arr1[0]]; // Mobile
$shop = $arr3[$arr1[1]]; // shop
$query="update table set shop='$shop', Mobile='$mobile'";

I think somebody will do in more elegant way. :)

Check array_count_values function.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.