Mifrau Posted November 8, 2018 Share Posted November 8, 2018 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! Quote Link to comment https://forums.phpfreaks.com/topic/307874-looping-through-an-array/ Share on other sites More sharing options...
kicken Posted November 9, 2018 Share Posted November 9, 2018 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. Quote Link to comment https://forums.phpfreaks.com/topic/307874-looping-through-an-array/#findComment-1562021 Share on other sites More sharing options...
Barand Posted November 9, 2018 Share Posted November 9, 2018 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; Quote Link to comment https://forums.phpfreaks.com/topic/307874-looping-through-an-array/#findComment-1562027 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.