Jump to content

Looping through an array


Mifrau

Recommended Posts

Hey!

 

So I recently started taking PHP classes because I was always somewhat interested in programming and finally wanted to take the first step. We are currently tasked with building a tool that can convert IP addresses into multiple different datatypes like bin and hexadecimal, all while keeping the general 'syntax' of an IP address.

 

I've tried around a bit but am facing two problems. The first one, most definitely major one is, that I can't seem to get a loop done that works through the array and converts it and the second problem is that I have no idea how to join them afterwards to get the original syntax back.

 

My current code looks like this

$ip = "127.0.0.1";

$ipArray = explode(".", $ip);

foreach($ipArray AS $convert){
 $convert = decbin($ipArray);
  $convertedArray = array($convert);
   $result = join($convertedArray);
}

echo $result;

I'd love any hints/help to get me back on track and into the right direction!

Link to comment
Share on other sites

You can use explode to split your IP, array_map to do the conversion, and implode to join them back together again. 

$ipComponents = explode('.', $ip);
$ipComponents = array_map('decbin', $ipComponents);
$ip = implode('.', $ipComponents);

The above would only work for IPv4 addresses.  If you need to support IPv6 you'll need to adjust the code accordingly.

 

Link to comment
Share on other sites

Here's a correction to your original attempt, so you can compare with yours and see where you went wrong

$ip = "127.0.0.1";

$ipArray = explode(".", $ip);
$converted = [];                       // array to store coverted values

foreach($ipArray AS $val){
    $converted[] = decbin($val);       // convert value and store in $converted array
   
}
$result = join('.', $converted);       // join converted array AFTER the loop has finished

echo $result;

 

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.