joehigh1
joehigh1

Reputation: 193

Convert single integer variable to a list of numbers (for example +/-3) with PHP

I was hoping to convert a single integer variable (coming in from a POST parameter) into a list, within a range of the original number, for example +/-3, using PHP.

So if var = 5 using PHP, output is = 2,3,4,5,6,7,8

or if var = 17 output is = 14,15,16,17,18,19,20

This is early guesswork, but I was thinking something like this:

<?php 

$single = $_POST['number'];

$mc = $single - 3;
$mb = $single - 2;
$ma = $single - 1;

$pa = $single + 1;
$pb = $single + 2;
$pc = $single + 3;

$list = [$mc, $mb, $ma, $single, $pa, $pb, $pc,]

echo $list

?>  

But it is just printing 'Array',

New to PHP, feel like I am overlooking a lot of things. Is it possible to assemble an array like this? Is there a quicker way to do what I'm trying?

Was hoping to do more like +/-30 .. was hoping there might be a shortcut / function that could help?

Upvotes: 0

Views: 300

Answers (3)

Progrock
Progrock

Reputation: 7485

You can use range for this.

<?php
$num   = filter_input(INPUT_GET, 'num', FILTER_VALIDATE_INT);
$range = 3;

if($num !== false) {
    $result = range($num-$range, $num+$range);
    echo implode(',', $result);
}

Output when (num is 2 and range is 3):

-1,0,1,2,3,4,5

Upvotes: 4

Martin
Martin

Reputation: 22760

Was hoping to do more like +/-30 .. was hoping there might be a shortcut / function that could help?

Yes, use a loop. Because you know the range you want, you can use a for loop:

NOTE: This code works with negative numbers, too.

$range = 3; // your given range
$value = (int)$_POST['number'];
$result = [];
$result[] = $value;

for ($i = 1; $i <= $range; $i++){
     $result[] = $value - $i ;
     $result[] = $value + $i;  
}

// Sort array and then output:

sort($result, SORT_NUMERIC);
 
print implode(', ', $result);// outputs a sorted list of values 
// Value = -2
// -5, -4, -3, -2, -1, 0, 1
//
// Value = 5
// 2, 3, 4, 5, 6, 7, 8  

Upvotes: 0

Dark Knight
Dark Knight

Reputation: 6541

Just use implode function after that.

$list = [$mc, $mb, $ma, $single, $pa, $pb, $pc];

echo implode(',', $list);

If you want to extend it for variable range too.

$single = 17;
$range = 3;
$data = range($single - $range, $single + $range);
echo implode(',', $data);

Upvotes: 1

Related Questions