php foreach 循环返回问题

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4385621/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 12:54:11  来源:igfitidea点击:

foreach loop return problem

phploopsforeach

提问by r1400304

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

谢谢

回答by Adrian Schmidt

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.

一个函数只能返回一次,因此您的函数将始终在第一次迭代时返回。如果您希望它在第一次匹配时返回 true,如果未找到匹配则返回 false,请尝试以下版本。

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

(您在如何使用 foreach 中的值方面也犯了错误,并且您忘记了 a }

回答by rik

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

应该是in_array($value, $array)。但你可以这样做count(array_intersect())

回答by Shakti Singh

you are passing first argument an array in in_array()it should be the value change it to

您传递的第一个参数是一个数组,in_array()其中的值应该是将其更改为

function findinArray($find,$array){
    foreach($find as $key => $value){
        if (in_array($value,$array)) {
            return true;
        }
        return false;
    }      
}