简体   繁体   中英

array_search recursive function php

I have this function which is supposed to generate random numbers and make sure they are not in the exceptions array, but I have this corner case:

It does not execute the while condition:

Exceptions Array
(
    [0] => 84
    [1] => 94
    [2] => 46

)

print_r ouput : number generated is 46 we have a match number im going to return is 84

so it does the first check correctly but not the recursive check, so it returns to me a duplicate value 84, is my while condition wrong?

function randWithout($from, $to, array $exceptions) {
    //sort($exceptions); // lets us use break; in the foreach reliably
    echo '<pre>';
    print_r($exceptions);
    echo '</pre>';
    $number = mt_rand($from, $to); 
    print_r('number generated is' . $number);
    if(array_search($number,$exceptions) != FALSE) 
    {
        echo 'we have a match';
        do {

            $number = mt_rand($from, $to);

        } while(array_search($number,$exceptions) === FALSE);
    }
    print_r('number im going to return is'. $number);
    return $number;
}

Ok here's what you should change it to:

$ex = [12,18,15];

for($i=0; $i<20;$i++) {
    print randWithout(10,20,$ex) . PHP_EOL;
}

function randWithout($from, $to, array $exceptions) {
    do {
        $number = mt_rand($from, $to);
    } while(in_array($number,$exceptions));

    return $number;
}

Just tested it and it works.

changed to:

if(in_array($number,$exceptions) != FALSE) 
    {
        echo 'we have a match';
        do {

            $number = mt_rand($from, $to);

        } while(in_array($number,$exceptions));
    }

Removed the == FALSE clause from in_array, as it returns true if needle is found.

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