Reputation: 693
I have a question about this situation, How could I store string via Array? this is my code
<?php
$octets = array($_POST["oct1"],$_POST["oct2"],$_POST["oct3"],$_POST["oct4"]);
$octlenfnl = count($octets) - 1;
$binoctstr = 0 ;
if($_POST["oct1"] <= 255 && $_POST["oct1"] <= 255 && $_POST["oct1"] <= 255 && $_POST["oct1"] <= 255)
{
for($i=0;$i<=$octlenfnl;$i++){
echo str_pad(decbin($octets[$i]), 8, '0', STR_PAD_LEFT) , " ";
}
}
else
{
echo "Invalid IP!";
}
?>
It outputs entered IP to Binary octets just like this 11111111 0001000 10010101 10010101
, they have spaces between the Octets, how can I split them and store it to array that is accessible globally?
Thanks
Upvotes: 1
Views: 2055
Reputation: 3288
isntead of echoing out your results store them into an array something like this
<?php
$octets = array($_POST["oct1"],$_POST["oct2"],$_POST["oct3"],$_POST["oct4"]);
$octlenfnl = count($octets) - 1;
$binoctstr = 0 ;
$binaryarray = array();
if($_POST["oct1"] <= 255 && $_POST["oct1"] <= 255 && $_POST["oct1"] <= 255 && $_POST["oct1"] <= 255)
{
for($i=0;$i<=$octlenfnl;$i++){
$binaryarray[] = str_pad(decbin($octets[$i]), 8, '0', STR_PAD_LEFT);
}
}
else
{
echo "Invalid IP!";
}
//to echo out your results you can do this as a comma separated string
echo implode(",",$binaryarray);
//or if you wish to access a specific segment you can do this where $key is the array element you want
echo $binaryarray[$key];
?>
UPDATE EDIT FOR SIMPLIFIED CODE
You can potentially simplfy the code a little I think like this save you creating a second array and just manipulating your existing array. Unless you need that initial array for anything this should work fine
<?php
$octets = array($_POST["oct1"],$_POST["oct2"],$_POST["oct3"],$_POST["oct4"]);
$binoctstr = 0 ;
if($_POST["oct1"] <= 255 && $_POST["oct1"] <= 255 && $_POST["oct1"] <= 255 && $_POST["oct1"] <= 255)
{
for($i=0;$i<=count($octets);$i++){
$octets [$i] = str_pad(decbin($octets[$i]), 8, '0', STR_PAD_LEFT);
}
}
else
{
echo "Invalid IP!";
}
//to echo out your results you can do this as a comma separated string
echo implode(",",$octets );
//or if you wish to access a specific segment you can do this where $key is the array element you want
echo $octets[$key];
?>
Upvotes: 1
Reputation: 14233
you can use $arr=explode(' ', "11111111 0001000 10010101 10010101");
Upvotes: 1