user1380566
user1380566

Reputation: 31

How to do multiple array_slice on a lengthy array?

I am very new to php. I am trying to do multiple array slices on a large array. Right now this is a section of my code:

$row1 = array_slice($filtered, 0, 22);
$row2 = array_slice($filtered, 22, 22);
$row3 = array_slice($filtered, 44, 22);
$row5 = array_slice($filtered, 66, 22);
$row6 = array_slice($filtered, 88, 22);
$row7 = array_slice($filtered, 110, 22);
$row8 = array_slice($filtered, 132, 22);
$row9 = array_slice($filtered, 154, 22);
$row10 = array_slice($filtered, 176, 22);

Each time the starting position of the array slice is 22 more than the previous row. Instead of writing out all of these rows (674 total) is there a statement that I can use to automatically advance the starting position 22 until it reaches an end, as well as assigning it to a variable that increases by 1 each time like the example. Thanks.

Upvotes: 3

Views: 1135

Answers (3)

Matt Morley - MPCM
Matt Morley - MPCM

Reputation: 278

Use array_chunk and then variable variables.

$j = 1;
foreach( array_chunk($list, 22)  as $chunk){
    ${"row{$j}"} = $chunk;
    $j++;
}

Upvotes: 0

John
John

Reputation: 529

You could use the php array_chunk function to split the original array into blocks of any size

i.e. $rows = array_chunk($filtered, 22);

Upvotes: 5

Michael Robinson
Michael Robinson

Reputation: 29498

$previous = 0;
$current = 22;
$rows = array();

for ($current; $current < size($filtered); $current+22) {
    $rows[] = array_slice($filtered, $previous, $current);
    $previous = $current;
}

You'll need a special case for when the $filtered array count is not divisible by 22.

Upvotes: 0

Related Questions