Splitting an array into columns
- 1 Min. Read.
Let’s assume we have the an array with the following values:
1 2 3 4 5 6 7 |
$iceCream = [ 'Vanilla', 'Cherry Vanilla', 'Strawberry', 'Mint Chocolate Chip', 'Chocolate Almond' ]; |
How would we divide these values over 3 columns using PHP?
The following function takes an array, the number of columns you want that array to be split in and a boolean that specifies if you want to preserve the keys in your array. After some calculations, you’ll get a new multidimensional array, containing your 3 columns.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
function splitIntoColumns($array, $numberOfColumns, $preserveKeys = false) { $i = 0; $columns = []; foreach ($array as $key => $val) { // We spread the values horizontally, not vertically, so we calculate the index every time $index = floor($i % $numberOfColumns); // Check if we want to preserve the keys if ($preserveKeys) { $columns[ $index ][$key] = $val; } else { $columns[ $index ][] = $val; } $i++; } return $columns; } |
This will output the following new array using our example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
Array ( [0] => Array ( [0] => Vanilla [3] => Mint Chocolate Chip ) [1] => Array ( [1] => Cherry Vanilla [4] => Chocolate Almond ) [2] => Array ( [2] => Strawberry ) ) |
And we can now loop over this new array with a nested for loop, and output some HTML to position the columns next to each other.
1 2 |
Vanilla | Cherry Vanilla | Strawberry Mint Chocolate Chip | Chocolate Almond | |