1

I have an array in PHP, Basically all I want to do is display the following array into ranges of 5. e.g: 0-5, 6-10, 11-15, 16-20, 21-25 etc:

Array
(
    [0] => 00
    [1] => 01
    [2] => 02
    [3] => 03
    [4] => 04
)

I have looked at the range() function - but this seems to output the single numbers from inputting a range. I'm sure this is really simple - thanks in advance:

After using arraychunk() I get the following output:

Array
(
    [0] => Array
    (
        [0] => 48
        [1] => 46
        [2] => 44
        [3] => 42
        [4] => 40
    )

    [1] => Array
    (
        [0] => 39
        [1] => 38
        [2] => 37
        [3] => 36
        [4] => 35
    )

    [2] => Array
    (
        [0] => 34
        [1] => 33
        [2] => 32
        [3] => 31
        [4] => 30
    )

    [3] => Array
    (
        [0] => 29
        [1] => 28
        [2] => 27
        [3] => 26
        [4] => 25
    )
)

This in theory works as I asked - however, these are actually years so in the first array chunk I looking to output years 1-5. My original array of numbers doesn't contain every year. e.g 1,3,4,6,7, not 1,2,3,4,5

2 Answers 2

1

If I have understood you correctly you may split array into chunks with array_chunk function

print_r(array_chunk($input_array, 5));
Sign up to request clarification or add additional context in comments.

2 Comments

This is perfect, but how would i add the label e.g. 0-5, 6-10 to each array chunk @zavg ?
you can store them as elements of other array with meaningful indexes (or just using the knowledge that i-st element of array represent elements in range [5*i; 5*(i+1)]
0

Try this. Use str_pad().

$nums = range(0, 99);
foreach ($nums as $v) {
    $arr[] = str_pad($v, 2, '0',STR_PAD_LEFT);
}
$res = array_chunk($arr, 5);
print_r($res);

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.