Jin Yong
Jin Yong

Reputation: 43778

how to get the last digit from the IP address?

Does anyone know how can I get the last digit number from the Ip address in php?

example:

$ip = '200.0.0.12';

How can I get only 12 from the IP address instead of 200.0.0.12?

Upvotes: 2

Views: 2629

Answers (3)

Roman Yakoviv
Roman Yakoviv

Reputation: 1724

My alternative. By this way you get last digit in number type, not in string

$ip = '200.0.0.12';
echo ip2long($ip) % 256;

Upvotes: 0

ChristopheD
ChristopheD

Reputation: 116237

I like Mike B's answer, but here's a possible alternative: use strrchr and substr:

$ip = '200.0.0.12';
echo substr(strrchr($ip,'.'),1);

One advantage: it's supposed to be (a little) faster then Mike B's answer.

In my (very unscientific) timings i got an average runtime of 1.3562 seconds (500.000 iterations) versus 1.6590 seconds for the array_pop / explode version.

Upvotes: 4

Mike B
Mike B

Reputation: 32155

Assuming the ip is well-formed (no ports, ipv4, etc)

$last_digit = array_pop(explode('.', $ip))

Upvotes: 6

Related Questions