How to Use In_Array If the Needle Is an Array

How can I use in_array if the needle is an array?

Use array_diff():

$arr1 = array(1,2,3);
$arr2 = array(1,2,3,4,5,6,7);
$arr3 = array_diff($arr1, $arr2);
if (count($arr3) == 0) {
// all of $arr1 is in $arr2
}

php in_array() with an array as needle producing unexpected results

Because the needle is an array in_array() is looking for an array in the haystack. The following works:

$needle =  array('fjord', 'troz');
//$haystack = array('troz', 'zort', 'fran', 'fjord');
$haystack = array(array("fjord","troz"), array("foo","bar"));
if (in_array($needle, $haystack))
{
echo "match found in the array";
}

EXAMPLE

How to use in_array in php with an array as needle but return true when there is at least one value match

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"

http://php.net/manual/en/function.array-intersect.php

Can I use PHP in_array with needle as array?

Yes. Example #3 for in_array() with an array as needle:

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

The real question is whether it will give you whatever results you may expect.

in_array() and multidimensional array

in_array() does not work on multidimensional arrays. You could write a recursive function to do that for you:

function in_array_r($needle, $haystack, $strict = false) {
foreach ($haystack as $item) {
if (($strict ? $item === $needle : $item == $needle) || (is_array($item) && in_array_r($needle, $item, $strict))) {
return true;
}
}

return false;
}

Usage:

$b = array(array("Mac", "NT"), array("Irix", "Linux"));
echo in_array_r("Irix", $b) ? 'found' : 'not found';

why does in_array return true when a value only begins with what is in an array

Because the in_array function uses the == operator. Thus 1 == "1thisisatest" - so, in_array will return true.

To fix this you can enabled strict mode:

// in the third parameter (to use === instead of ==)
in_array($search_value, $array_name, true)`


Related Topics



Leave a reply



Submit