循环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
}
};
答
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.