1

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.

Cain Nuke
  • 2,843
  • 5
  • 42
  • 65

3 Answers3

2
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.

Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175
Poomrokc The 3years
  • 1,099
  • 2
  • 10
  • 23
0

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;
  }

  }

?>
Azeem Hassni
  • 885
  • 13
  • 28
0
<?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;
}
?>
Swapnil Deo
  • 241
  • 1
  • 3
  • 16