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.

Introduction

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.

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

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

/*
OUTPUT
Array
(
    [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.

<?php
$arr = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K"];
 
print_r(array_slice($arr, 1, 3));
 
/*
OUTPUT
Array
(
    [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"=>"shorturl.at/iDEL4", "alt"=>"a screen with colorful code"],
    ["title"=>"Open Sign in Window", "url"=>"shorturl.at/pAFUW", "alt"=>"a window with open sign"],
    ["title"=>"Reading Glasses", "url"=>"shorturl.at/vyKV5", "alt"=>"reading glasses on top of a book"],
    ["title"=>"A Camel", "url"=>"shorturl.at/sGOP3", "alt"=>"a camel"],
    ["title"=>"A Heart Model", "url"=>"shorturl.at/couB2", "alt"=>"a heart model"],
    ["title"=>"Laptop on a Desk", "url"=>"shorturl.at/ghyLV", "alt"=>"a laptop on a desk"],
    ["title"=>"Shaman", "url"=>"shorturl.at/pzIQY", "alt"=>"shaman"],
    ["title"=>"Holding Bitcoin", "url"=>"shorturl.at/guO16", "alt"=>"holding a bitcoin"],
    ["title"=>"A Zebra", "url"=>"shorturl.at/hjyAD", "alt"=>"a zebra"],
    ["title"=>"A Tiger", "url"=>"shorturl.at/chzHQ", "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))];
 
/*
OUTPUT
[
{"title":"Reading Glasses","url":"shorturl.at\/vyKV5","alt":"reading glasses on top of a book"},
{"title":"A Camel","url":"shorturl.at\/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);
}
 
print_r(html_image_generator($selected_chunk));
 
/*
OUTPUT
Array
(
    [0] => <img src ="shorturl.at/pzIQY" alt = "shaman"/>
    [1] => <img src ="shorturl.at/guO16" 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.

<html>
    <head>
        <title>Two Random Images</title>
    </head>
    <body>
        <img src ="shorturl.at/pzIQY" alt = "shaman"/>
        <img src ="shorturl.at/guO16" alt = "holding a bitcoin"/>
    </body>
</html>

Conclusion

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.