How to split a multidimensional array in PHP

Last Updated on

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


Arrays can hold many values. Sometimes we may need chunks of a long-running list. A straightforward approach would be looping through an array and making chunks of it based on hard-coded pointers. However, PHP features built-in functions that could save us all this hassle.

This article explores the answer to how to split an array in PHP. We will see a couple of helpful PHP functions to help us split a multidimensional array of images. An HTML image generator function will turn these array images into an HTML image element.

array to html images

So let’s dive into the main subject and explore this concept in depth.

How to split a multidimensional array in PHP with array_chunk

PHP array_chunk splits an array into chunks. Here is its signature.

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

The length argument determines the size of each chunk, with the last chunk being an exception. If an array is not evenly divisible, the last chunk’s count is less than the length argument. The last argument determines if the keys should be kept intact after splitting an array.

Example of array_chunk in PHP

The following example demonstrates the use of array_chunk in PHP.

$arr = ['One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten'];
$chunks = array_chunk($arr, 2);

The length is two implying that every chunk gets two elements. Let’s see the output of this example.

    [0] => Array
            [0] => One
            [1] => Two
    [1] => Array
            [0] => Three
            [1] => Four
    [2] => Array
            [0] => Five
            [1] => Six
    [3] => Array
            [0] => Seven
            [1] => Eight
    [4] => Array
            [0] => Nine
            [1] => Ten

Voila! That’s awesome. PHP array_chunk seems to be really helpful. Let’s not stop here and move to another function that helps in slicing out chunks from a  multidimensional array in PHP.

How to split a multidimensional array in PHP with array_slice

PHP array_slice slices a chunk out of an array. It doesn’t return a well-chunked array but only one chunk that we’re interested in, potentially factoring out the rest of the array.

array_slice( array $array, int $offset, ?int $length = null, bool $preserve_keys = false): array

The array_slice function has an offset and length argument. These two arguments can come up in different combinations. Starters could have a difficult time wrapping their heads around all the fuss involved when these two arguments lead to an unexpected outcome. 

For better understanding, we recommend you to go through the FuelingPHP article about array_slice in PHP. The following example is just a basic one and perhaps easily understandable.

$arr = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K"];
print_r(array_slice($arr, 1, 3));
    [0] => B
    [1] => C
    [2] => D

The offset of one point to “B” and the length of three includes elements from “B” to “D”, thus the outcome is [“B” , “C” ,” D”].

How to split a multidimensional array in PHP?

Now as we are familiar with array_chunk and array_slice in PHP, let’s jump to a scenario that involves a multidimensional array of images, as shown below.

//Suppose these images are loaded from an image API.
$images = [
    ["title"=>"Colorful Code", "url"=>"", "alt"=>"a screen with colorful code"],
    ["title"=>"Open Sign in Window", "url"=>"", "alt"=>"a window with open sign"],
    ["title"=>"Reading Glasses", "url"=>"", "alt"=>"reading glasses on top of a book"],
    ["title"=>"A Camel", "url"=>"", "alt"=>"a camel"],
    ["title"=>"A Heart Model", "url"=>"", "alt"=>"a heart model"],
    ["title"=>"Laptop on a Desk", "url"=>"", "alt"=>"a laptop on a desk"],
    ["title"=>"Shaman", "url"=>"", "alt"=>"shaman"],
    ["title"=>"Holding Bitcoin", "url"=>"", "alt"=>"holding a bitcoin"],
    ["title"=>"A Zebra", "url"=>"", "alt"=>"a zebra"],
    ["title"=>"A Tiger", "url"=>"", "alt"=>"a tiger"],

Let’s say want to split the array into chunks of two, all we need now is to call PHP array_chunk with the length argument set to two. The function can easily split this multidimensional array.

After that, we pick up a chunk at random as the following example demonstrates.

$images_chunks = array_chunk($images, 2);
$selected_chunk = $images_chunks[rand(0, count($images_chunks))];
{"title":"Reading Glasses","url":"\/vyKV5","alt":"reading glasses on top of a book"},
{"title":"A Camel","url":"\/sGOP3","alt":"a camel"}

Voila! We have a random chunk. Next, we will look into an HTML image generator function that eventually consumes this chunk and returns an array of HTML images.

function html_image_generator($images)
    return array_map(function($img) {
        $src = $img["url"];
        $alt = $img["alt"];
        return '<img src ="'. $src  .'" alt = "'. $alt. '"/>';
    }, $images);
    [0] => <img src ="" alt = "shaman"/>
    [1] => <img src ="" alt = "holding a bitcoin"/>

Perfect! This function and all the associate business logic in this module resides in this file. You can import the function in the main HTML template and the function will inject the images in it. Finally, here’s a bare bone HTML with these two random images.

        <title>Two Random Images</title>
        <img src ="" alt = "shaman"/>
        <img src ="" alt = "holding a bitcoin"/>


This article focuses on how to split a multidimensional array in PHP. First, it overviews PHP array_chunk with an example followed by array_slice in PHP. Finally, it features a multidimensional array of images. This array_chunk splits this array. Next, we pick a random chunk and pass it on to a function that turns it into an HTML image.

Interesting, wasn’t it? The article shows how to split a multidimensional array with some really cool examples. If you want to learn more about PHP through intuitive and in-depth content then hit up at FuelingPHP.

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.