简体   繁体   English

为什么我的函数总是返回false?

[英]why does my function always return false?

why does my function always return false? 为什么我的函数总是返回false? i think the problem is caused by the isset function but i really dont know how to fix it 我认为问题是由isset函数引起的,但我真的不知道如何解决它

$big = array(
2,3,5,7,11,13,17,19,23
,29,31,37);

$fbig = array_flip ($big);


function isprime($n){
    if($n < 2){
        return FALSE;
    }
    if($n > 2147483647){
        return FALSE;
    }
    if($n < 46341){ 
        if(isset($fbig[$n])){


            return TRUE;
        } else {
            return FALSE;
        }
    }
}

$b = 11;
if(isprime($b)){echo "lol";}
if(isset($fbig[$n])){

This line is the problem. 这条线就是问题所在。

  1. What you want to check is not isset($fbig[$n]) (which checks if there is something in the array at the index $n ) but in_array($n, $fbig) (which checks if the array $fbig contains the value $n ). 你要检查的不是isset($fbig[$n]) (它检查索引$n中的数组中是否有东西)但是in_array($n, $fbig) (检查数组$fbig包含价值$n )。

  2. The array $fbig is not in the scope of the function since it's defined outside. 数组$fbig不在函数范围内,因为它是在外部定义的。 But you can pass it: 但你可以通过它:

if(isprime($b, $fbig)){echo "lol";}

should work just fine. 应该工作得很好。

because your looking for a key, not a value 因为你在寻找钥匙,而不是价值

$fbig[11] is not set $fbig[11]未设置

you'll want to use in_array() 你想要使用in_array()

in this case, there are 11 items, but they are numbered from 0-10, no 11 在这种情况下,有11个项目,但它们编号从0-10,没有11

plus, like Sarfraz said, it needs to be global 另外,像Sarfraz说的那样,它需要是全球性的

It's because your function doesn't know what $fbig is. 这是因为你的函数不知道$ fbig是什么。 A quick fix would be to change your function to look like this: 快速解决方法是将您的功能更改为如下所示:

function isprime($n){

    global $fbig;

    if($n < 2){
        return FALSE;
    }
    if($n > 2147483647){
        return FALSE;
    }
    if($n < 46341){ 
         return isset($fbig[$n]); // Nit picking fix!
    }
}

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

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