PHP 中的递归函数
我的 PHP 递归函数有问题。我的功能的目的是将 IP 地址与 IP 地址范围进行比较。这是我的两个变量的数据模型:
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
)
)
我知道迭代方法可能会更好,但它仅用于使用递归方法进行训练。
所以这是我的代码:
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);
}
我不知道为什么,但是当我测试我的函数时,它总是给我一个错误的返回。
if (checkRangeIp($ip_array, $range_ip_array))
echo "TRUE\n";
else
echo "FALSE\n";
我该如何解决这个问题?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您有一个
checkRangeIp
退出路径,它不返回任何值(即递归调用)。将其替换为否则函数调用将在
if(...)
条件内被评估为false
。注意:看起来您以某种方式混淆了
true
和false
。如果值超出范围,则条件($nb1 < $nb2 || $nb1 > $nb3)
为 true,在这种情况下,函数返回true
。You have an exit path of
checkRangeIp
which does not return any value (namely the recursive call). Replace it byotherwise the function call will be evaluated as
false
inside yourif(...)
condition.Note: It looks like you mixed up somehow
true
andfalse
. The condition($nb1 < $nb2 || $nb1 > $nb3)
is true if the value lies outside of the range and in this case the function returnstrue
.