Php: Create an Array for a Range

PHP: Create an array for a range

This can be solved by using a simple for loop:

//  Start ↓    End ↓  Step ↓
for ($i = 1; $i <= $num; ++$i) {
$array[] = $i;
}

range of numbers from array

<?php

$array = [33,34,35,36,66,67,68,69,89,90,91,92,93];

$min = $array[0];
$currentRange = 0;
$ranges = [];

foreach ($array as $element) {
if($min+1 < $element) {
$currentRange++;
}

$ranges[$currentRange][] = $element;
$min = $element;
}

var_dump($ranges);

Output:

array(3) {
[0]=>
array(4) {
[0]=>
int(33)
[1]=>
int(34)
[2]=>
int(35)
[3]=>
int(36)
}
[1]=>
array(4) {
[0]=>
int(66)
[1]=>
int(67)
[2]=>
int(68)
[3]=>
int(69)
}
[2]=>
array(5) {
[0]=>
int(89)
[1]=>
int(90)
[2]=>
int(91)
[3]=>
int(92)
[4]=>
int(93)
}
}

How do I create an array for a range of values with keys using php?

This will form your array correctly using array_combine:

$array = array_combine( range(1,1000), range(1,1000));

How to generate an array of strings numbers with a specific range

Use array_map

<?php
$range = range('0000000000', '9999999999', '1111111111');
var_dump(array_map('strval',$range));

This will return:

array(10) {
[0]=>
string(1) "0"
[1]=>
string(10) "1111111111"
[2]=>
string(10) "2222222222"
[3]=>
string(10) "3333333333"
[4]=>
string(10) "4444444444"
[5]=>
string(10) "5555555555"
[6]=>
string(10) "6666666666"
[7]=>
string(10) "7777777777"
[8]=>
string(10) "8888888888"
[9]=>
string(10) "9999999999"
}

Alternatively, for 0 to be returned as 0000000000, (as per @Franz Gleichmann comments)

<?php
$range = range('0000000000', '9999999999', '1111111111');
$rangeElements = array_map(function($range) {
return str_pad($range, 10, '0', STR_PAD_LEFT);
}, $range);
var_dump($rangeElements);

or

<?php
$range = range('0000000000', '9999999999', '1111111111');
$rangeElements = array_map(function($range) {
return sprintf('%010d', $range);
}, $range);
var_dump($rangeElements);

so output:

array(10) {
[0]=>
string(10) "0000000000"
[1]=>
string(10) "1111111111"
[2]=>
string(10) "2222222222"
[3]=>
string(10) "3333333333"
[4]=>
string(10) "4444444444"
[5]=>
string(10) "5555555555"
[6]=>
string(10) "6666666666"
[7]=>
string(10) "7777777777"
[8]=>
string(10) "8888888888"
[9]=>
string(10) "9999999999"
}

Create a price range from an array

Use array_sum(array_column($prices['options'], 'count')) to retrieve the total counts from each of the price options.

Use array_column($prices['options'], 'value'); to extract the values from the array, that can be used to sort or sum the values of.

Sort the prices by the values from lowest to highest using array_multisort($values, SORT_ASC, SORT_NATURAL, $prices['options']);

Extract the highest and lowest values from the sorted array, by using reset() and end() of the resulting sorted array.

Alternatively in PHP 7.3+ use array_key_first() and array_key_last() respectively.

$values[array_key_first($values)];
$values[array_key_last($values)];

Use explode('_') on the highest and lowest values and retrieve the indexed offset of [0] or [1] of the first or last position of the separated values.

$counts = array_sum(array_column($prices['options'], 'count'));

$values = array_column($prices['options'], 'value');
array_multisort($values, SORT_ASC, SORT_NATURAL);

$lowest = explode('_', reset($values))[0];
$highest = explode('_', end($values))[1];

/* PHP 7.3+
$lowest = explode('_', $values[array_key_first($values)])[0];
$highest = explode('_', $values[array_key_last($values)])[1];
*/

$prices['options'] = [
'label' => $lowest . '-' . $highest,
'value' => $lowest . '_' . $highest,
'count' => $counts
];

var_export($prices['options']);

Result: https://3v4l.org/PmXg3

PHP 7.3+: https://3v4l.org/iTbcq

array (
'label' => '0-500',
'value' => '0_500',
'count' => 2564,
)


Ambiguous Ranges

In the event you have ambiguous ranges, where the upper and lower bounds can be the same, EG: 100-200 and 100-600 or 100-600 and 200-600. Each lower and upper value would need to be extracted without needing to rely on sorting.

PHP 7.2 + Example: https://3v4l.org/a8BCL#v7.2.34

$counts = array_sum(array_column($prices['options'], 'count'));

$values = [];
foreach ($prices['options'] as $priceOption) {
[$values[], $values[]] = explode('_', $priceOption['value']);
}
$lower = min($values);
$upper = max($values);

$prices['options'] = [
'label' => $lower . '-' . $upper,
'value' => $lower . '_' . $upper,
'count' => $counts,
];

PHP array - range key

Using array_fill():

<?php

$data = [
1 => 1000,
2 => 500,
3 => 250
];

$a = array_fill(4,2, 100);
$b = array_fill(6,5, 50);
$c = array_fill(11,89, 20);

$data = $data + $a + $b + $c;

print_r($data);

Create Alphanumeric Range in PHP

You can do it with array_map and range:

$prefix = "A";
$arr = array_map(function ($e) use ($prefix) { return $prefix . strval($e);}, range(1,4));

Or as a function:

function alphanumericRange($prefix, $start, $end)
{
return array_map(function ($e) use ($prefix) {return $prefix . strval($e);}, range($start, $end));
}

How to dynamically create an array of 10 to 100 with gap of 10 between values?

You could use range(). The third argument is the number to step between values when interpolating between the start and ending values.

$numbers = range(10, 100, 10); 

How can I get specific range of array just in specific range index by PHP?

I found a simple solution after several tests:

foreach($my_arr as $indx=>$val )
{
if(is_int($indx) && ($indx>=0 && $indx<=4))
{
$my_arr[$indx]= $val;
}
else
{ continue; }

}

Converting array elements into range in php

You have to code it yourself ;-)

The algorithm is quite simple:

  • Iterate over the items.
  • Remember the previous item and the start of the range.
  • For each item (except the first one) check:
    • If currentItem = prevItem + 1 then you haven't found a new range. Continue.
    • Otherwise your range has ended. Write down the range. You have remembered the start of the range. The end is the previous item. The new range starts with the current item.
    • The first item always starts a new range. Remember this one as start of the range.
  • Don't forget to write down the current range when leaving the loop.


Related Topics



Leave a reply



Submit