How to Use array_chunk with foreach loop with PHP Code Example

Last Updated on

CraftyTechie is reader-supported. When you buy through links on our site, we may earn an affiliate commission.

PHP array_chunk with foreach loop Code Examples

PHP array_chunk function helps partition an array in chunks. The length argument defines the length for the chunks. If the array is not evenly divisible, the last chunk could have less than the specified length. 

The article “array_chunk with examples”  explains everything you need to know about this function. Nonetheless, the article includes a recap of the function to set the ground for the rest of the sections.

This article features a scorecard use case where we may need array_chunk with foreach loop. Stay with us till the end to get the most out of this article.

<?php
$names_score = [
    "Tyson" => 9,
    "Jackie" => 10,
    "Ron" => 15,
    "Maximillian" => 20,
    "Sus" => 24,
    "Ryder" => 25
];
 
$names_score_chunks = array_chunk($names_score, 2, true); //Sets the preserve key argument to true.
 
/*
OUTPUT
[
    [
        "Tyson" => 9,
        "Jackie" => 10
    ],
    [
        "Ron" => 15,
        "Maximillian" => 20,
    ],
    [
        "Sus" => 24,
        "Ryder" => 25
    ]
]
*/
?>

Have you tried any of the following highly relevant Pluralsight PHP Courses?

We love Pluralsight because it has thousands of high-quality course content and is extremely affordable. You don’t have to pay for individual courses. It’s a really small monthly membership and you get access to the entire catalog. You can track and review all of your progress and also obtain additional certifications.

Courses

  • PHP Design Patterns
  • PHP: The Big Picture
  • PHP 8: Web Application Security
  • High-Performance PHP
  • Object-Oriented PHP

Learning Paths:

  • PHP Development Fundamentals

Pluralsight Free Trial

Curious about Pluralsight but not ready to commit? We understand. We were able to get a free trial for you to test-drive and see all of their courses. Click on the link below

Try a Pluralsight free trial for 7 days!

PHP array_chunk – Overview

The array_chunk in PHP splits an array into chunks. Following is the function signature.

array_chunk(array $array, int $length, bool $preserve_keys = false): array

Arguments

  • $array – The input array.
  • $length – The size of each chunk.
  • $preserve_keys – When true, the function preserves the keys.

Important Note

If the function couldn’t split an array evenly, the last chunk gets lesser elements than the preceding chunks.

Example – 1

Following is a basic usage example of array_chunk PHP.

<?php
$numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
 
$numbers_chunks = array_chunk($numbers, 5); //Every chunk should have five elements.
 
/*
OUTPUT
[
    [1, 2, 3, 4, 5],
    [6, 7, 8, 9, 10]
]
*/
?>

Voila! The function is easy but super helpful in partitioning arrays in PHP. 

Example – 2

The following example demonstrates how to preserve array keys while using PHP array_chunk.

<?php
$names_score = [
    "Tyson" => 9,
    "Jackie" => 10,
    "Ron" => 15,
    "Maximillian" => 20,
    "Sus" => 24,
    "Ryder" => 25
];
 
$names_score_chunks = array_chunk($names_score, 2, true); //Sets the preserve key argument to true.
 
/*
OUTPUT
[
    [
        "Tyson" => 9,
        "Jackie" => 10
    ],
    [
        "Ron" => 15,
        "Maximillian" => 20,
    ],
    [
        "Sus" => 24,
        "Ryder" => 25
    ]
]
*/
?>

Setting the $preserve_keys arguments help in keeping the keys intact. The next section includes a scenario where array_chunk with foreach loop helps lay out some HTML tables.

PHP array_chunk with foreach – A Usecase

Let’s see the $names_score array again. First, we sort it in descending order as follows.

arsort($names_score);
 
/*
Array
(
    [Ryder] => 25
    [Sus] => 24
    [Maximillian] => 20
    [Ron] => 15
    [Jackie] => 10
    [Tyson] => 9
)
*/

Learn more about array sorting at FuelingPHP. The goal here is to make separate HTML lists for three categories of players.

  1. Gold – Players with score between 21 to 30 inclusive
  2. Silver – Players with score between 11 to 20 inclusive.
  3. Bronze – Players with score between 1 to 10 inclusive.

The array_chunk splits the array into three categories already seen in the example above. The next objective is to populate HTML lists using these chunks. The following examples demonstrate how to do so with the array_chunk foreach loop.

$categories = ['Gold', 'Silver', 'Bronze'];
 
$styles = ['#ffff99', '#e0e0eb', '#d2a679'];
 
foreach(array_chunk($names_score, 2, true) as $k => $v)
{
    echo "<div>
            <h1 style = 'color: $styles[$k];'> $categories[$k] Category Players </h1>
            <ul>";
        foreach($v as $name=>$score) {
            echo "<li>$name $score</li>";
        }
    echo "</ul></div>";
 
}

The foreach loop iterates over the array chunks, and the nested foreach loop maps every chunk to the list elements.

Following is the output of this example.

<div>
    <h1 style = 'color: #ffff99;'> Gold Category Players </h1>
    <ul>
        <li>Ryder 25</li>
        <li>Sus 24</li>
    </ul>
</div>
<div>
    <h1 style = 'color: #e0e0eb;'> Silver Category Players </h1>
    <ul>
        <li>Maximillian 20</li>
        <li>Ron 15</li>
    </ul>
</div>
<div>
    <h1 style = 'color: #d2a679;'> Bronze Category Players </h1>
    <ul>
        <li>Jackie 10</li>
        <li>Tyson 9</li>
    </ul>
</div>

Voila! The example lays out the HTML pretty well. Here’s how the output seems when viewed in the browser. Note that the HTML above is only a fragment of the view. We have done some extra work to set the view but this fragment is copied to the main file as it is.

array_chunk with foreach loop

Perfect! We know it is a simple view yet a good use case for demonstrating array_chunk with foreach loop.

Conclusion

The article explains how to use array_chunk with foreach loop in PHP. It includes an overview of the PHP array_chunk function. Following the review, the article includes a use case for laying out a scorecard in HTML using array_chunk with foreach loop.

That’s all for this article. To learn more about PHP stay tuned as FuelingPHP features articles and tutorials that can help you scale up your PHP knowledge.

Want to learn more about PHP?

We have many fun articles related to PHP. You can explore these to learn more about PHP.

Did you find this article helpful?

Join the best weekly newsletter where I deliver content on building better web applications. I curate the best tips, strategies, news & resources to help you develop highly-scalable and results-driven applications.

Build Better Web Apps

I hope you're enjoying this article.

Get the best content on building better web apps delivered to you.