array_partition

array_partition Install Statistics

0
100%
Today: 0 Yesterday: 0 All-time: 2,993 downloads
array_partition Icon

Try plugin: array_partition

We'll create fresh WordPress site with array_partition installed. You have 20 minutes to test the plugin after that site we'll be deleted.

Takes ~10 seconds to install.

About array_partition

Provides a helper function to split an array into N number of evenly distributed partitions (i.e. split a list into N columns)

0


0


0


0


0

updated: 1 year ago
since: 15 years ago
author: Scott Reilly

Description

This plugin provides the PHP function c2c_array_partition() to split an array into any number of sub-arrays, suitable for creating evenly distributed, vertically filled “columns”. Also known as “chunking” or “partitioning”.

For example:

$topics = array( "aardvark", "bear", "cat", "dog", "emu", "fox", "gnu", "hippo", "ibis", "jackal" );
print_r( c2c_array_partition( $topics, 4 ) );

Yields:

Array
(
    [0] => Array
        (
            [0] => ant
            [1] => bear
            [2] => cat
        )

    [1] => Array
        (
            [0] => dog
            [1] => emu
            [2] => fox
        )

    [2] => Array
        (
            [0] => gnu
            [1] => hippo
        )

    [3] => Array
        (
            [0] => ibis
            [1] => jackal
        )
)

Note the array elements are distributed into the requested 4 “columns” as evenly as possible.

The function will fill as many partitions as requested, as long as there are enough elements in the array to do so. Any remaining unfilled partitions will be represented as empty arrays.

In contrast, using PHP’s built-in array_chunk() as such:

print_r( array_chunk( $topics, 4 ) );

Yields:

Array
(
    [0] => Array
        (
            [0] => aardvark
            [1] => bear
            [2] => cat
            [3] => dog
        )
    [1] => Array
        (
            [0] => emu
            [1] => fox
            [2] => gnu
            [3] => hippo
        )
    [2] => Array
        (
            [0] => ibis
            [1] => jackal
        )
)

It can be sent an array of any data types or objects.

Links: Plugin Homepage | Plugin Directory Page | GitHub | Author Homepage

Examples

<?php
  $topics = array( "ant", "bear", "cat" );
  print_r( c2c_array_partition( $topics, 5 ) );
?>

=>

Array
(
    [0] => Array
        (
            [0] => ant
        )

    [1] => Array
        (
            [0] => bear
        )

    [2] => Array
        (
            [0] => cat
        )

    [3] => Array
        (
        )

    [4] => Array
        (
        )
)

Also see Description section for another example. Definitely check out the packaged unit test file as it contains various examples.