[nycphp-talk] I need a function that will compare IP addresses

Chris Shiflett shiflett at
Mon Aug 18 12:51:36 EDT 2003

--- Phil Powell <soazine at> wrote:
> have written a function that is supposed to compare the first three
> nodes of an IP address, but it is riddled with errors that I have
> given up trying to figure out.
> Is there an existing function out there that can do this? I want to
> compare "" with "" and come with as a "match",
> or "" with "", but no "match if "" and
> "".

This probably isn't the best solution, since it's just ad hoc email coding
(untested, etc.), but it seems a bit better than what you were trying:

$ip1 = '';
$ip2 = '';

$ip1_array = explode('.', $ip1);
$ip2_array = explode('.', $ip2);

$ip1_array['3'] = '';
$ip2_array['3'] = '';

$ip1 = implode('.', $ip1_array);
$ip2 = implode('.', $ip2_array);

if ($ip1 == $ip2)
     echo "First three octets are identical\n";

I'm sure there is a cooler way to compare the two using logical bitwise stuff,
but this might be easier to understand.

Hope that helps.


Become a better Web developer with the HTTP Developer's Handbook

More information about the talk mailing list