1

I want to loop through an array in Php and get 3 items at a time, for example if an array contains these numbers: [1,2,3,4,5,6,7,8,9,10,11] then I want to be able to loop through it and get 3 at a time, but if the list does not break evenly into 3's then get whatever is left over.

So, in this example I would want (1,2,3), (4,5,6), (7,8,9), (10, 11). What is the easiest way to do this? This is what I have so far which is getting just one item at a time from the array:

            for ($w = 0; $w < count($decoded_photos); $w++) {
                $photo_reference = $decoded_photos[$w]["photo_reference"];
                echo "photo reference " . $photo_reference;    
            }
0

1 Answer 1

2

It looks like what you're looking for is exactly what the array_chunk method does.

Have a look here: https://www.php.net/manual/en/function.array-chunk.php

In your case:

$array = [1, 2, 3, 4, 5, 6, 7, 8, 9 , 10, 11];
$chunked_array = array_chunk($array, 3);
print_r($chunked_array);

Will return

Array
(
    [0] => Array
        (
            [0] => 1
            [1] => 2
            [2] => 3
        )

    [1] => Array
        (
            [1] => 4
            [2] => 5
            [3] => 6
        )
   ...
)

Once you have the chunked array you can just loop over that and then output all 3 keys at a time:

foreach ($chunked_array as $key => $value) {
   echo $value[0];
   echo $value[1];
   echo $value[2];
}
Sign up to request clarification or add additional context in comments.

1 Comment

This question is a duplicate -- as all basic question are after millions of questions and over 10 years of answers.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.