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?

1
  • There's a whack of array functions for this: array_merge, array_diff, array_intersect, etc... Commented Oct 3, 2014 at 18:05

5 Answers 5

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.

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

1 Comment

I don't have more complex data just numbers thats why I posted an example like this. And thanks it worked.
1

This is the conditional you are looking for:

if (count(array_diff($arr2, $arr1)) == 0) {

1 Comment

Thanks, I like your answer but I already accepted one when I saw yours.
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
}

Comments

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!

Comments

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

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.