im using array_diff
to check if ALL needles exist
// my code
$needle = array(' b', 'asb');
$haystack = array('a','b','c','d','e');
if (empty(array_diff($needle, $haystack))) {
echo "The NEEDLE is in HAYSTACK";
}else {
echo "The NEEDLE is NOT in HAYSTACK";
// return 'asb'
}
how do i return the needle is not in haystack? or is there any way to do this?
As you already have checked if all of the needles exist, you can just return a string using implode()
to join the missing values into some form of list. I've extracted the array_diff()
out so that you can re-use the value...
$needle = array('b', 'asb');
$haystack = array('a','b','c','d','e');
$difference = array_diff($needle, $haystack);
if (empty($difference)) {
echo "The NEEDLE is in HAYSTACK";
}else {
echo "The NEEDLE is NOT in HAYSTACK ";
echo implode (",", $difference);
}
Note for the test data in this code, I have removed the space before the b
in the $needle
variable. As ' b'
also doesn't exist in the $haystack
.