简体   繁体   中英

why does my function always return false?

why does my function always return false? i think the problem is caused by the isset function but i really dont know how to fix it

$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 ).

  2. The array $fbig is not in the scope of the function since it's defined outside. 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

you'll want to use in_array()

in this case, there are 11 items, but they are numbered from 0-10, no 11

plus, like Sarfraz said, it needs to be global

It's because your function doesn't know what $fbig is. 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!
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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