Reputation: 3103
im looking for a function like array_intersect but instead of returning what values are present in 2 arrays it should return TRUE only if all values in array 1 are contained in array 2.
For example:
$first_array = array(0=>1, 1=>4, 2=>8)
$second_array = array(0=>9, 1=>8, 2=>7, 3=>1, 4=>3, 5=>4)
If you compare both arrays, all the values in $first_array are present in $second_array which are 1, 4 and 8 so the function should return true. Is there a function out there that can do this?
Thank you.
Upvotes: 1
Views: 585
Reputation: 1099
function compare($first_array, $second_array){
if(empty(array_diff($first_array,$second_array))){
return true;
}else{
return false;
}
}
Try this. Anyone see any error please edit it.
Upvotes: 2
Reputation: 281
<?php
function compare($arr1,$arr2)
{
$arr3=Array();
$k=0;
for($i=0;$i<count($arr1);$i++)
{
if(in_array($arr1[$i],$arr2))
$arr3[$k]=$arr1[$i];
$k++
}
if(count($arr3)==count($arr1))
return true;
else
return false;
}
?>
Upvotes: 0
Reputation: 886
Here is solution
if you don't want to use array_diff()
<?php
$a = array("c","b","a");
$b = array("a","b","c");
if(ArrayCompare($a , $b)){
echo "100%";
} else {
echo "NOT";
}
function ArrayCompare($array1 , $array2) {
$c = 0;
foreach($array1 as $v) {
if(in_array($v , $array2)) {
$c++;
}
}
if(count($array2) == $c) {
return true;
} else {
return false;
}
}
?>
Upvotes: 0