Jump to content

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
https://forums.phpfreaks.com/topic/307874-looping-through-an-array/
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.

 

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;

 

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.