简体   繁体   English

PHP in_array函数不起作用

[英]PHP in_array function doesn't work

I have some problems with in_array() I want to create a unique number from 100-999 that is not stored in the array already, but the in_array function does not seem to work. 我在使用in_array()时遇到一些问题,我想从100-999创建一个唯一的数字,该数字尚未存储在数组中,但是in_array函数似乎不起作用。 The example below is what my code is right now. 下面的示例是我现在的代码。

I have pushed 2 strings to the array in the top. 我已经将2个字符串推到顶部的数组中。 In the function, I try to run it, but just get the value "sb100", and I should get "sb102" because 100 and 101 are already in the array. 在函数中,我尝试运行它,但只获取值“ sb100”,而我应该得到“ sb102”,因为数组中已经有100和101。

$uniqueIDs[] = "sb100";
$uniqueIDs[] = "sb101";

function keyExists($ui){
    for($i=100;$i<=999;$i++){
        $R = "sb".$i;
        if(in_array($R, $ui)){
            return "";
        }else{
            return $R; 
            break;
        }
    }
}    

keyExists($uniqueIDs);

The problem is that as when it finds an element that already exists, it does return ""; 问题在于,当它找到一个已经存在的元素时,它确实会return ""; . Instead you just continue if it's in the array and return if it isn't the array... 相反,如果它在数组中,则继续操作,如果不是数组,则返回...

function keyExists($ui){
    for($i=100;$i<=999;$i++){
        $R = "sb".$i;
        if(!in_array($R, $ui)){
            return $R;
        }
    }
}
$uniqueIDs[] = "sb100";
$uniqueIDs[] = "sb101";

function keyExists($ui){
   for($i=100;$i<=999;$i++){
        $R = "sb".$i;
        if(!in_array($R, $ui)){
           return $R; 
       }
   }

} }

echo keyExists($uniqueIDs);

You shouldn't return if match... 如果匹配,您不应该回来...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM