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?
You have an exit path of
checkRangeIpwhich does not return any value (namely the recursive call). Replace it byotherwise the function call will be evaluated as
falseinside yourif(...)condition.Note: It looks like you mixed up somehow
trueandfalse. The condition($nb1 < $nb2 || $nb1 > $nb3)is true if the value lies outside of the range and in this case the function returnstrue.