如何在php中使用in_array并将数组作为needle,但在至少有一个值匹配时返回true
问题描述:
Here is my in_array
code
$array = array('a', 'b', 'c');
if(in_array(array('p', 'c'), $array)){
echo "found";
}else{
echo "not found";
}
it returns not found, but actually I want it to return found
, because there is one value match c
.
这是我的 它返回未找到,但实际上我希望它返回 in_array code>代码 p>
$ array = array('a','b','c');
if(in_array(array('p','c'),$ array)){
echo“found”;
}其他{
echo“not found”;
}
code> pre>
found ,因为有一个值匹配
c code>。 p>
div>
答
Your idea can be realized by using array_intersect
and count
functions.
If there's at least one matched item between two arrays - count
will return the number of matched items (1 or more):
$needle = array('p', 'c');
$haystack = array('a', 'b', 'c');
echo (count(array_intersect($needle, $haystack))) ? "found" : "not found";
// will output: "found"
答
use array_interset()
:-
$search = array('p', 'c');
$array = array('a', 'b', 'c');
$result = !empty(array_intersect($search , $array ));
var_dump($result); // print result
//OR
if(count($result) >=1){echo 'found';}else{'not found';}
Output:-https://eval.in/599429
Reference:-
答
Another approach by creating a user function
function found_in_array($needle, $haystack) {
foreach ($needle as $array) {
if(in_array($array, $haystack)){
return "found";
}
}
return "not found";
}
$haystack = array('a', 'b', 'c');
$needle = array('p', 'c');
echo found_in_array($needle, $haystack);