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 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算