0

Where am I wrong?

The code looks OK, but the function returns 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);
    }
}
Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
Ned
  • 1

1 Answers1

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);
    }
}
  • Thanks Himanshu Patel! I have missed a return in the recursion. – Ned Oct 13 '17 at 17:12
  • 5
    Yes, you might want to add an explanation instead of just dumping code. – AbraCadaver Oct 13 '17 at 17:18
  • An explanation would be in order. E.g., what is the idea/gist? From [the Help Center](https://stackoverflow.com/help/promotion): *"...always explain why the solution you're presenting is appropriate and how it works"*. Please respond by [editing (changing) your answer](https://stackoverflow.com/posts/46734754/edit), not here in comments (***without*** "Edit:", "Update:", or similar - the answer should appear as if it was written today). – Peter Mortensen May 26 '22 at 17:22