Reputation: 33
This code should return TRUE
value:
<?php
$return = in_array(array(1, 2), array(1, 2));
?>
but in_array
returns FALSE.
Upvotes: 2
Views: 3188
Reputation: 48091
in_array
checks if a value exists in an array.
Your $needle
doens't exists at all as a value of $haystack
that would be ok if your $haystack
was
array(1,2,3,array(1,2))
Notice in this case array(1,2)
actually is found inside as expected
If you want to check whenever 2 arrays are equal i suggest you the ===
operator
($a === $b) // TRUE if $a and $b have the same key/value pairs in the same order and of the same types.
Upvotes: 13
Reputation: 342635
Are you interested in intersection?
$arr1 = array(1, 2);
$arr2 = array(1, 2);
$return = array_intersect($arr1, $arr2);
if(count($return) === count($arr1)) {
// all are present in arr2
}
Upvotes: 3
Reputation: 6852
In your case, the first parameter of in_array should not be an array, but an integer. What you are doing with that code is checking for the presence of an array inside the array, which is not there. A correct form would be:
in_array(1, array(1, 2)); // true
Upvotes: 1
Reputation: 327
array(1,2) is not in array(1,2) it is array(1,2),
$return = in_array(array(1, 2), array(array(1, 2)));
would return true. (more an extension of yes123's answer)
Upvotes: 2
Reputation: 54016
if second array looks like this
array(array(1, 2));
then return true
Upvotes: 1
Reputation: 30731
you missunderstand in_array see offiziell docs: http://uk.php.net/in_array
<?php
$a = array(array('p', 'h'), array('p', 'r'), 'o');
if (in_array(array('p', 'h'), $a)) {
echo "'ph' was found\n";
}
if (in_array(array('f', 'i'), $a)) {
echo "'fi' was found\n";
}
if (in_array('o', $a)) {
echo "'o' was found\n";
}
?>
Upvotes: 2
Reputation: 11478
Your first array isn't contained in the second array, it's equal.
This returns true:
var_dump(in_array(array(1, 2), array(1, 2, array(1, 2))));
Upvotes: 4
Reputation: 134167
According to the PHP Manual for in_array
, the function's syntax is:
bool in_array ( mixed $needle , array $haystack [, bool $strict = FALSE ] )
So you need to supply a $needle
value as the first argument. This explains why your example returns FALSE. However, these examples will each return TRUE:
in_array(1, array(1, 2));
in_array(2, array(1, 2));
in_array(array(1, 2), array(1, 2, array(1, 2)))
That said, it might help if you explain exactly what you are trying to do. Perhaps in_array
is not the function you need.
Upvotes: 4
Reputation: 72971
Based on your example, you may want to look into array_intersect(). It compares arrays in a fashion that may better align with your spec.
Upvotes: 5
Reputation: 673
First parameter is the value you're looking for in the second parameter (array) http://php.net/manual/fr/function.in-array.php
Upvotes: 2