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.

1

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, that looks nice. Would this also work? if(array_diff($first_array, $second_array)==0 { return TRUE};
@CainNuke sorry , that's beyond my knowledge. You need to try it yourself.
It works for me, seems like we get the same results with both methods. I like yours better though. Thank you.
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;
  }

  }

?>

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.