1

I'm trying to check if an array doesn't have other values than the other but in_array() didn't worked so I guess it can't be done with in_array();

for example

<?php
$arr1 = array(1,2,3,4,5,6);
$arr2 = array(1,2,9);
if(/*all values in $arr2 are in $arr1*/){ 
  /*return true*/
}
else{
  /*return false*/
}
/*this examle should return false*/
?>

or

<?php
$arr1 = array(1,2,3,4,5,6);
$arr2 = array(1,2,6);
if(/*all values in $arr2 are in $arr1*/){ 
  /*return true*/
}
else{
  /*return false*/
}
/*this examle should return true*/
?>

how can I do this?

Laci K
  • 585
  • 2
  • 8
  • 24
  • There's a whack of array functions for this: array_merge, array_diff, array_intersect, etc... – Marc B Oct 03 '14 at 18:05

5 Answers5

1

Use this

count($array) == count(array_intersect($array,$valid));

.. or come to think of it;

$array == array_intersect($array,$valid);

Note that this would yield true if (string)$elementtocheck=(string)$validelement, so in essence, only usable for scalars. If you have more complex values in your array (arrays, objects), this won't work. To make that work, we alter it a bit:

sort($array);//order matters for strict
sort($valid);
$array === array_intersect($valid,$array);

... assuming that the current order does not matter / sort() is allowed to be called.

Community
  • 1
  • 1
XoMEX
  • 321
  • 2
  • 7
  • I don't have more complex data just numbers thats why I posted an example like this. And thanks it worked. – Laci K Oct 03 '14 at 18:15
1

This is the conditional you are looking for:

if (count(array_diff($arr2, $arr1)) == 0) {
Dallas Caley
  • 5,367
  • 6
  • 40
  • 69
0

You can use array_intersect() function:

if (array_intersect($arr1, $arr2) == $arr2) {
  // $arr2 has only elements from $arr1
} else {
  // $arr2 has not only elements from $arr1
}
0

Try array_diff:

Example

public function checkSameContents($arr1, $arr2) {
    $diff = array_diff($arr1, $arr2); // returns "unsame" elements in array 
    return count($diff) === 0;
}

This function will return true if the arrays have the same contents, but false if not.

Hope this helps!

-1

Have you tried

$arr1 == $arr2

Or you can use a function

<?php
function compareArrays(Array $a, Array $b){
  if(count($a) != count($b)){
    return false;
  }
  foreach($a as $value){
    if( !in_array($value, $b) ){
      return false;
    }
  }
  return true;
}
?>

This is only an example but you could do it this way.

Genmais
  • 1,099
  • 2
  • 9
  • 14