-1

I have a variable that lists multiple IPs, such as this:

$ip_list = "8.8.8.8, 50.66.30.88, 28.24.56.33";

How can I get just the first IP from the list? For example, if I just wanted to echo 8.8.8.8 in the example above.

The number of IPs may vary, but I always just want to get the first one.

Andrew
  • 665
  • 2
  • 8
  • 11

3 Answers3

2

you can simply use explode and get the first item ?

$ip_list = "8.8.8.8, 50.66.30.88, 28.24.56.33";
$ipArray = explode(",", $ip_list);
echo trim($ipArray[0]);
Achayan
  • 5,720
  • 2
  • 39
  • 61
  • 1
    you may in addition trim the result `trim($ipArray[0])` to remove leading and trailing whitespaces – r3bel Mar 15 '17 at 00:26
1
$ips = explode(",", $ip_list);
echo $ips[0];//8.8.8.8

You must use explode or split.

Nikita Davidenko
  • 160
  • 2
  • 12
0

This question is already answered here : How can I split a comma delimited string into an array in PHP?

Still you can go with split or explode. Using explode others have already shown. Using split you will first need to find the position of the comma(,) and only then you will be able to split it.

print_r(str_split("Hello",3));

This will print this as an output. Here, 3 should be your location of comma.

arr[0] -> Hel arr[1]->lo
Community
  • 1
  • 1
Resheil Agarwal
  • 155
  • 1
  • 11