0

In PHP, I have lines of code given below.

<?php
$num_array = [1,2,3,4,5,6,7];

function generate_random_number($length){
  if($length > 15){
    $length = 15;
  }
  return rand(pow(10, $length-1), pow(10, $length)-1);
}

// if random number is less than 5 then return that number else call this function again.
function recurse(){
    $rand = generate_random_number(1);
    if($rand < 5){
        echo '(recurse happened) ';
      recurse();
    }else{
        return $rand;  
    }  
}

// loopinig seven times
foreach ($num_array as $number) {
    var_dump(recurse());
    echo '<br>';
}
?>

Problem -
If recurse() function calls itself again then in foreach loop it prints NULL instead of waiting for the next result.
You can see my output (If you will run then you will get different output) -.

int(5)
int(9)
int(7)
(recurse happened) NULL
(recurse happened) NULL
int(7)
int(9)

Why is this happening and what's the solution ?

Abhishek kamal
  • 101
  • 1
  • 1
  • 9

0 Answers0