0

i'm trying to generate a firewall template from a php config

i've got this array

$config=array('1024','3306','3804','127017');

and i would like this output

1024:3305
3307:3803
3805:127017

as you can see, the first and last value stay the same, the value in between are -1 / +1

i think i can do it but not in a clean way, i tried to manipulate the array but in a wrong way i guess because the code is too verbose

may you help ?

thanks

3
  • 3
    Can you please show us your code , that you have tried ? Commented Dec 10, 2015 at 15:53
  • Do you want your output as a string or as a new array? Commented Dec 10, 2015 at 15:58
  • for now i've got nothing to show sorry... @tommy as a string Commented Dec 10, 2015 at 16:01

4 Answers 4

1
$config=array('1024','3306','3804','127017');

$output = [];

foreach ($config as $k => $port) {
    if (isset($config[$k+1])) {
        $output[] = ($k ? $port + 1 : $port)
            . ':'
            . (isset($config[$k+2]) ? ($config[$k + 1] - 1) : $config[$k + 1]);
    }
}

echo implode("<br>", $output);
Sign up to request clarification or add additional context in comments.

Comments

0
$config=array('1024','3306','3804','127017');

for ($i=0; $i<sizeof($config); $i++) {
    if ($i == 0) {
        echo $config[$i] . ":";
    } elseif($i == (sizeof($config)-1)) {
        echo $config[$i];
    } else {
        echo ($config[$i]-1)."<br />".($config[$i]+1).":";
    }
}

Comments

0

I'd recommend storing the values in an associative array first so that you can use this data for further operations. Output it in a second step:

$config = ['1024','3306','3804','127017'];

$result = [];
for ($i = 0, $count = count($config) - 2; $i <= $count; ++$i)
{
    $key = $i == 0 ? $config[$i] : $config[$i] + 1;
    $value = $i == 0
        ? $config[$i + 1] - 1
        : (
            $i == $count ? $config[$i + 1] : $config[$i + 1] - 1
        );
    $result[$key] = $value;
}

// Output it:
foreach ($result as $key => $value)
{
    echo "$key:$value <br>";
}

Comments

0

Simply:

<?php 
$config=array('1024','3306','3804','127017');

$c = count($config);
for ($n = 0; $n<$c-1; $n++) {
    printf(
        '%d:%d'.PHP_EOL,
        ($n==0 ? $config[0] : $config[$n]+1),        // use incremented value if not first
        ($n==$c-2 ? $config[$c-1] : $config[$n+1]-1) // use decremented value if not last
    );
}

If you want to output to the browser, you will have to add a <br> tag in the printf() template.

See it in action.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.