php简单递归返回null

时间:2017-10-13 16:41:33

标签: php recursion null return

我哪里错了? 代码看起来没问题,但函数返回NULL。

$ar = array(1, 2, 3, 4, 5, 6, 7, 8, 9);
$n = 6;

$new_n = chckn($n, $ar);

echo $new_n;

function chckn($n, $ar){
    if(!in_array($n, $ar)){
        echo "===$n===\n";
        return $n;
    } else {
        $n = rand(1,10);
        chckn($n, $ar);
    }
}

1 个答案:

答案 0 :(得分:1)

$ar = array(1, 2, 3, 4, 5, 6, 7, 8, 9);
$n = 6;

$new_n = chckn($n, $ar);

echo $new_n;

function chckn($n, $ar){
    if(!in_array($n, $ar)){
        //echo "===$n===\n";
        return $n;
    } else {
        $n = rand(1,10);
        return chckn($n, $ar);
    }
}