开发者

foreach loop return problem

开发者 https://www.devze.com 2023-01-29 04:48 出处:网络
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

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")){
         ec开发者_C百科ho "Match";
}

thanks


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 })


It should be in_array($value, $array). But you could just do count(array_intersect()).


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;
    }      
}
0

精彩评论

暂无评论...
验证码 换一张
取 消