-1

I have a problem with my recursive function in PHP. The aim of my function is to compare an IP address with a range of IP addresses. Here is my data model for the two variables:

Array
(
   [0] => 150
   [1] => 2
   [2] => 0
   [3] => 155
)
Array
(
   [0] => Array
       (
           [0] => 150
           [1] => 26
           [2] => 0
           [3] => 0
       )

   [1] => Array
       (
           [0] => 150
           [1] => 100
           [2] => 255
           [3] => 255
       )
)

I know the iterative method will be probably better, but it's just for training with recursive methods.

So here is my code:

function checkRangeIp($ip_array, $range_ip_array, $recur_it = 0) {
  if ($recur_it == 4)
    return false;

  $nb1 = $ip_array[$recur_it];
  $nb2 = $range_ip_array[0][$recur_it];
  $nb3 = $range_ip_array[1][$recur_it];

  if ($nb1 < $nb2 || $nb1 > $nb3)
    return true;
  else
    checkRangeIp($ip_array, $range_ip_array, $recur_it + 1);
}

I don't know why, but when I test my function it always giving me a false return.

if (checkRangeIp($ip_array, $range_ip_array))
  echo "TRUE\n";
else
  echo "FALSE\n";

How can I fix this problem?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Jeffrey Muller
  • 850
  • 1
  • 15
  • 28
  • If you are just comparing each range pair, then it's not something that lends itself to recursion. Make it a loop instead. – mario Dec 29 '11 at 11:39
  • Your function only returns `true` if `$nb1 < $nb2 || $nb1 > $nb3`. This is not the case for the first value, `150`. So instead of returning, it calls `checkRangeIp` again, but you are not returning the return value of that call, so it will just return nothing. That said, even if this is fixed I don't think that your range check is correct, and this is really not a problem with a recursive solution. – Felix Kling Dec 29 '11 at 11:40

1 Answers1

1

You have an exit path of checkRangeIp which does not return any value (namely the recursive call). Replace it by

return checkRangeIp($ip_array, $range_ip_array, $recur_it + 1);

otherwise the function call will be evaluated as false inside your if(...) condition.

Note: It looks like you mixed up somehow true and false. The condition ($nb1 < $nb2 || $nb1 > $nb3) is true if the value lies outside of the range and in this case the function returns true.

Howard
  • 38,639
  • 9
  • 64
  • 83