Reputation:
hi i write a function to find in array but its not working when loop find something match its not retuning true value checks to the end any idea
function findinArray($find,$array){
foreach($find as $key => $value){
if (in_array($find,$array)) {
return true;
}else{
return false;
} }
}
if(findinArray(array("a","b"),array("a")){
echo "Match";
}
thanks
Upvotes: 4
Views: 39068
Reputation: 1885
A function can only return once, so your function will always return on the first iteration. If you want it to return true on the first match, and false if no match was found, try the version below.
function findinArray($find, $array) {
foreach ($find as $value) {
if (in_array($value, $array)) {
return true;
}
}
return false;
}
if (findinArray(array("a","b"), array("a")) {
echo "Match";
}
(You had also made errors in how you use the values in the foreach, and you have forgotten a }
)
Upvotes: 15
Reputation: 86366
you are passing first argument an array in in_array()
it should be the value
change it to
function findinArray($find,$array){
foreach($find as $key => $value){
if (in_array($value,$array)) {
return true;
}
return false;
}
}
Upvotes: -1
Reputation: 8612
It should be in_array($value, $array)
. But you could just do count(array_intersect())
.
Upvotes: 5