Reputation: 1231
I want to compare two arrays and want to get the number of values matched in PHP. e.g
$a1 = array(one, two, three);
$a2 = array(two, one, three);
If i compare these arrays i should get 0
difference as result. Can anybody help
Thanks in advance.
Upvotes: 0
Views: 422
Reputation: 1125
i made an simple function for you
This function will give you the repeated and unrepeated data
i used contries as example
$contries1=array('egypt','america','england');
$contires2=array('egypt','england','china');
function countryRepeated($contries1,$contires2,$status='1'){
foreach($contries1 as $country){
if(in_array($country,$contires2))
$repeated[]=$country;
else
$unrepeated[]=$country;
}
return ($status=='1')?$repeated:$unrepeated;
}
To get the repeated contries use
print_r(countryRepeated($contries1,$contires2));
Results:
Array ( [0] => egypt [1] => england )
Or if you would like to get the unreapeated contries
You can use:
print_r(countryRepeated($contries1,$contires2,'2'));
Results:
Array ( [0] => america )
Upvotes: 0
Reputation: 635
I hope this helps
$diff = count(array_diff($a1, $a2));
$matches = count($a1) - $diff;
Refer: PHP array comparison
Upvotes: 1
Reputation: 6573
$a1 = array( 1, 2, 3, 4 );
$a2 = array( 2 , 1, 3, 8 );
$matched = array_intersect( $a1, $a2 );
var_dump( $matched );
this should output:
Array
(
[0] => 1
[1] => 2
[2] => 3
)
array_intersect will give you all the elements or the first array that exist in the second - using the keys of the first array
Upvotes: 1
Reputation: 9299
$arr1 = array('one', 'two', 'three');
$arr2 = array('two', 'one', 'three');
echo "number of differences : " . count(array_diff($arr1, $arr2));
Upvotes: 1