doubu1950 2016-10-27 13:44
浏览 97
已采纳

循环foreach / else语句

I have an foreach statement in php, the code checks if an ip is in any of the ranges given, if it is echo 1, this works fine.

However i would like to add an else for this, so if the ip does not match any of the arrays then echo 2.

This is not working as it seems to echo 2 for each of the ranges it does not match so it echos 222 which is undesired.

How do i do have it so if in range echo 1 else if not in range echo 2

$range = (object) array();
    $range->name = 'test1';
    $range->lower = '10.1.5.78';
    $range->upper = '10.1.5.78';
    $public_ip_ranges[] = $range;

    $range = (object) array();
    $range->name = 'test2';
    $range->lower = '146.127.0.0';
    $range->upper = '146.127.255.255';
    $public_ip_ranges[] = $range;


    if (($lngIP=ip2long($ip)) < 0) $lngIP += 4294967296;

    foreach ($public_ip_ranges as $ip_range) {
       if (($lngLow=ip2long($ip_range->lower)) < 0) $lngLow += 4294967296;
       if (($lngHigh=ip2long($ip_range->upper)) < 0) $lngHigh += 4294967296;
       if($lngIP >= $lngLow and $lngIP <= $lngHigh) {
           echo 1;
        } else {
            echo 2;
            break
        }
    };
  • 写回答

1条回答 默认 最新

  • doubanduo7620 2016-10-27 13:49
    关注

    You can do something like this:

    $range = (object) array();
    $range->name = 'test1';
    $range->lower = '10.1.5.78';
    $range->upper = '10.1.5.78';
    $public_ip_ranges[] = $range;
    
    $range = (object) array();
    $range->name = 'test2';
    $range->lower = '146.127.0.0';
    $range->upper = '146.127.255.255';
    $public_ip_ranges[] = $range;
    
    
    if (($lngIP=ip2long($ip)) < 0) $lngIP += 4294967296;
    
    foreach ($public_ip_ranges as $ip_range) {
       if (($lngLow=ip2long($ip_range->lower)) < 0) $lngLow += 4294967296;
       if (($lngHigh=ip2long($ip_range->upper)) < 0) $lngHigh += 4294967296;
       if($lngIP >= $lngLow && $lngIP <= $lngHigh) {
            $result = 1;
            break;
        } else {
            $result = 2;
            break;
        }
    }
    echo $result;
    

    On this case you are just printing $result as last result of loop. There are also breaks, if you dont want to continue.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计
  • ¥15 路易威登官网 里边的参数逆向
  • ¥15 Arduino无法同时连接多个hx711模块,如何解决?
  • ¥50 需求一个up主付费课程
  • ¥20 模型在y分布之外的数据上预测能力不好如何解决
  • ¥15 processing提取音乐节奏
  • ¥15 gg加速器加速游戏时,提示不是x86架构
  • ¥15 python按要求编写程序
  • ¥15 Python输入字符串转化为列表排序具体见图,严格按照输入